@soulcraft/brainy 0.9.23 → 0.9.26

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.
@@ -6,7 +6,7 @@ var e="undefined"!=typeof window?window:this;function t(e,t){return t.forEach(fu
6
6
  * @author Feross Aboukhadijeh <https://feross.org>
7
7
  * @license MIT
8
8
  */
9
- function(e){const t=o,n=m,r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=i,e.SlowBuffer=function(e){+e!=e&&(e=0);return i.alloc(+e)},e.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,i.prototype),t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=s(n);const a=r.write(e,t);a!==n&&(r=r.slice(0,a));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);const a=function(e){if(i.isBuffer(e)){const t=0|p(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||Y(e.length)?s(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return u(e),s(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=s(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,i.prototype),r}function p(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function f(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let a=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(a)return r?-1:j(e).length;t=(""+t).toLowerCase(),a=!0}}function g(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return $(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return N(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,a){let s,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(u(e,s)===u(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(u(e,s+r)!==u(t,r)){n=!1;break}if(n)return s}return-1}function w(e,t,n,r){n=Number(n)||0;const a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(Y(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return K(j(t,e.length-n),e,n,r)}function k(e,t,n,r){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function I(e,t,n,r){return K(q(t),e,n,r)}function S(e,t,n,r){return K(function(e,t){let n,r,a;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function N(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let a=t;for(;a<n;){const t=e[a];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(a+o<=n){let n,r,i,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[a+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[a+1],r=e[a+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[a+1],r=e[a+2],i=e[a+3],128==(192&n)&&128==(192&r)&&128==(192&i)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&i,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),a+=o}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(e,t,n){return function(e,t,n){return u(e),e<=0?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}(e,t,n)},i.allocUnsafe=function(e){return l(e)},i.allocUnsafeSlow=function(e){return l(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=i.allocUnsafe(t);let a=0;for(n=0;n<e.length;++n){let t=e[n];if(X(t,Uint8Array))a+t.length>r.length?(i.isBuffer(t)||(t=i.from(t)),t.copy(r,a)):Uint8Array.prototype.set.call(r,t,a);else{if(!i.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,a)}a+=t.length}return r},i.byteLength=f,i.prototype._isBuffer=!0,i.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},i.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},i.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},i.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(i.prototype[r]=i.prototype.inspect),i.prototype.compare=function(e,t,n,r,a){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0);const c=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){s=u[e],o=l[e];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return b(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return b(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function $(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function C(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function R(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let a="";for(let r=t;r<n;++r)a+=Q[e[r]];return a}function A(e,t,n){const r=e.slice(t,n);let a="";for(let e=0;e<r.length-1;e+=2)a+=String.fromCharCode(r[e]+256*r[e+1]);return a}function _(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function O(e,t,n,r,a){V(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function F(e,t,n,r,a){V(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function M(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,a,23,4),r+4}function B(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,a,52,8),r+8}i.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,i.prototype),r},i.prototype.readUintLE=i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUintBE=i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e+--t],a=1;for(;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUint8=i.prototype.readUInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),this[e]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readBigUInt64LE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,a=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(a)<<BigInt(32))}),i.prototype.readBigUInt64BE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],a=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(a)}),i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=t,a=1,s=this[e+--r];for(;r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readBigInt64LE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),i.prototype.readBigInt64BE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),i.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUint8=i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigUInt64LE=J(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}let a=0,s=1,o=0;for(this[t]=255&e;++a<n&&(s*=256);)e<0&&0===o&&0!==this[t+a-1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}let a=n-1,s=1,o=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigInt64LE=J(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const a=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),a},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{const s=i.isBuffer(e)?e:i.from(e,r),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=s[a%o]}return this};const L={};function z(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function W(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function V(e,t,n,r,a,s){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){U(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,a,s)}function U(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw U(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}z("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),z("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,a=n;return Number.isInteger(n)&&Math.abs(n)>2**32?a=W(String(n)):"bigint"==typeof n&&(a=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(a=W(a)),a+="n"),r+=` It must be ${t}. Received ${a}`,r},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function j(e,t){let n;t=t||1/0;const r=e.length;let a=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,r){let a;for(a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let a=0;a<16;++a)t[r+a]=e[n]+e[a]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(s);const y=new Uint8Array(16);function b(){if(!g&&(g="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(y)}const x=[];for(let e=0;e<256;++e)x.push((e+256).toString(16).slice(1));var w={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v(e,t,n){if(w.randomUUID&&!e)return w.randomUUID();const r=(e=e||{}).random||(e.rng||b)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+"-"+x[e[t+4]]+x[e[t+5]]+"-"+x[e[t+6]]+x[e[t+7]]+"-"+x[e[t+8]]+x[e[t+9]]+"-"+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]}(r)}const k=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>{const a=n-t[r];return e+a*a},0);return Math.sqrt(n)},I=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const{dotProduct:n,normA:r,normB:a}=e.reduce((e,n,r)=>({dotProduct:e.dotProduct+n*t[r],normA:e.normA+n*n,normB:e.normB+t[r]*t[r]}),{dotProduct:0,normA:0,normB:0});if(0===r||0===a)return 2;return 1-n/(Math.sqrt(r)*Math.sqrt(a))},S=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");return e.reduce((e,n,r)=>e+Math.abs(n-t[r]),0)},N=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>e+n*t[r],0);return-n};async function T(e,t,n=k){if(t.length<10)return t.map(t=>n(e,t));try{return t.map(t=>n(e,t))}catch(r){return console.error("Batch distance calculation failed:",r),t.map(t=>n(e,t))}}function E(){return"undefined"!=typeof window&&"undefined"!=typeof document}function $(){return"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node}function C(){return E()&&"undefined"!=typeof Worker||function(){if(!$())return!1;try{return require("worker_threads"),!0}catch(e){return!1}}()}const R=new Map;function A(e,t){if($())return function(e,t){return new Promise((n,r)=>{try{import("node:worker_threads").then(({Worker:a,isMainThread:s,parentPort:o,workerData:i})=>{if(!s&&o){const e=new Function("return "+i.fnString)()(i.args);return void o.postMessage({result:e})}const c=`worker-${Math.random().toString(36).substring(2,9)}`;let u;if(R.size<4)u=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),R.set(c,u);else{const n=Array.from(R.keys()),r=n[Math.floor(Math.random()*n.length)];u=R.get(r),u._busy&&(u.terminate(),u=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),R.set(r,u)),u._busy=!0}u.on("message",e=>{u._busy=!1,n(e.result)}),u.on("error",e=>{u._busy=!1,r(e)}),u.on("exit",e=>{0!==e&&(u._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(E()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{const a=new Blob(["\n self.onmessage = function(e) {\n try {\n const fn = new Function('return ' + e.data.fnString)();\n const result = fn(e.data.args);\n self.postMessage({ result: result });\n } catch (error) {\n self.postMessage({ error: error.message });\n }\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(a),o=new Worker(s);o.onmessage=function(e){e.data.error?r(new Error(e.data.error)):n(e.data.result),o.terminate(),URL.revokeObjectURL(s)},o.onerror=function(e){r(new Error(`Worker error: ${e.message}`)),o.terminate(),URL.revokeObjectURL(s)},o.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{const n=new Function("return "+e)();return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function _(){$()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of R.values())e.terminate();R.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let D=class{constructor(){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu"}async init(){try{const e=console.warn;console.warn=function(t,...n){t&&"string"==typeof t&&t.includes("Hi, looks like you are running TensorFlow.js in Node.js")||e(t,...n)},this.tf=await Promise.resolve().then(function(){return vy}),await Promise.resolve().then(function(){return rS});try{if("undefined"!=typeof window){await Promise.resolve().then(function(){return FD});try{this.tf.setBackend?(await this.tf.setBackend("webgl"),this.backend="webgl",console.log("Using WebGL backend for TensorFlow.js")):console.warn("tf.setBackend is not available, falling back to CPU")}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}}}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}this.tf.setBackend&&await this.tf.setBackend(this.backend),this.use=await Promise.resolve().then(function(){return mF}),console.log("Universal Sentence Encoder module structure in main thread:",Object.keys(this.use),this.use.default?Object.keys(this.use.default):"No default export");const t=function(e){console.log("Universal Sentence Encoder module structure:",Object.keys(e),e.default?Object.keys(e.default):"No default export");let t=null;if(e.load&&"function"==typeof e.load)t=e.load,console.log("Using sentenceEncoderModule.load");else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load,console.log("Using sentenceEncoderModule.default.load");else if(e.default&&"function"==typeof e.default)t=e.default,console.log("Using sentenceEncoderModule.default as function");else if("function"==typeof e)t=e,console.log("Using sentenceEncoderModule as function");else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load,console.log("Using sentenceEncoderModule.UniversalSentenceEncoder.load");else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.default.UniversalSentenceEncoder.load,console.log("Using sentenceEncoderModule.default.UniversalSentenceEncoder.load");else for(const n in e)if("function"==typeof e[n]){if((e[n].name||n).toLowerCase().includes("load")){t=e[n],console.log(`Using sentenceEncoderModule.${n} as load function`);break}}else if("object"==typeof e[n]&&null!==e[n]){for(const r in e[n])if("function"==typeof e[n][r]){if((e[n][r].name||r).toLowerCase().includes("load")){t=e[n][r],console.log(`Using sentenceEncoderModule.${n}.${r} as load function`);break}}if(t)break}return t}(this.use);if(!t)throw new Error("Could not find Universal Sentence Encoder load function");this.model=await t(),this.initialized=!0,console.warn=e}catch(e){throw console.error("Failed to initialize Universal Sentence Encoder:",e),new Error(`Failed to initialize Universal Sentence Encoder: ${e}`)}}async embed(e){this.initialized||await this.init();try{let t;if("string"==typeof e){if(""===e.trim())return new Array(512).fill(0);t=[e]}else{if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new Error("UniversalSentenceEncoder only supports string or string[] data");if(0===e.length||e.every(e=>""===e.trim()))return new Array(512).fill(0);if(t=e.filter(e=>""!==e.trim()),0===t.length)return new Array(512).fill(0)}const n=await this.model.embed(t),r=await n.array();return n.dispose(),r[0]}catch(e){throw console.error("Failed to embed text with Universal Sentence Encoder:",e),new Error(`Failed to embed text with Universal Sentence Encoder: ${e}`)}}async embedBatch(e){this.initialized||await this.init();try{if(0===e.length)return[];const t=e.filter(e=>"string"==typeof e&&""!==e.trim());if(0===t.length)return e.map(()=>new Array(512).fill(0));const n=await this.model.embed(t),r=await n.array();n.dispose();const a=[];let s=0;for(let t=0;t<e.length;t++){const n=e[t];"string"==typeof n&&""!==n.trim()?(a.push(r[s]),s++):a.push(new Array(512).fill(0))}return a}catch(e){throw console.error("Failed to batch embed text with Universal Sentence Encoder:",e),new Error(`Failed to batch embed text with Universal Sentence Encoder: ${e}`)}}async dispose(){if(this.model&&this.tf)try{this.model.dispose(),this.tf.disposeVariables(),this.initialized=!1}catch(e){console.error("Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function O(e){return async t=>await e.embed(t)}const F=new D;let M=!1;function P(){return async e=>{try{return M||(await F.init(),M=!0),await F.embed(e)}catch(e){throw console.error("Failed to use TensorFlow embedding:",e),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}const B=P(),L=new D;let z=!1;const W=async e=>{try{return z||(await L.init(),z=!0),await L.embedBatch(e)}catch(e){throw console.error("Failed to use TensorFlow batch embedding:",e),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}};function V(e){const t=O(e);return async e=>{const n=t.toString();return await A(n,e)}}var U=Object.freeze({__proto__:null,UniversalSentenceEncoder:D,createEmbeddingFunction:O,createTensorFlowEmbeddingFunction:P,createThreadedEmbeddingFunction:V,defaultBatchEmbeddingFunction:W,defaultEmbeddingFunction:B});const G={M:16,efConstruction:200,efSearch:50,ml:16};class H{constructor(e={},t=k,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...G,...e},this.distanceFunction=t,this.useParallelization=void 0===n.useParallelization||n.useParallelization}setUseParallelization(e){this.useParallelization=e}getUseParallelization(){return this.useParallelization}async calculateDistancesInParallel(e,t){if(!this.useParallelization||t.length<10)return t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}));try{const n=t.map(e=>e.vector),r=await T(e,n,this.distanceFunction);return t.map((e,t)=>({id:e.id,distance:r[t]}))}catch(n){return console.error("Error in GPU-accelerated distance calculation, falling back to sequential processing:",n),t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}))}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");if(null===this.dimension)this.dimension=n.length;else if(n.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${n.length}`);const r=this.getRandomLevel(),a={id:t,vector:n,connections:new Map};for(let e=0;e<=r;e++)a.connections.set(e,new Set);if(0===this.nouns.size)return this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;if(!this.entryPointId)return console.error("Entry point ID is null"),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;const s=this.nouns.get(this.entryPointId);if(!s)return console.error(`Entry point with ID ${this.entryPointId} not found`),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;let o=s,i=this.distanceFunction(n,s.vector);for(let e=this.maxLevel;e>r;e--){let t=!0;for(;t;){t=!1;const r=o.connections.get(e)||new Set;for(const e of r){const r=this.nouns.get(e);if(!r)continue;const a=this.distanceFunction(n,r.vector);a<i&&(i=a,o=r,t=!0)}}}for(let e=Math.min(r,this.maxLevel);e>=0;e--){const r=await this.searchLayer(n,o,this.config.efConstruction,e),s=this.selectNeighbors(n,r,this.config.M);for(const[n,r]of s){const r=this.nouns.get(n);r&&(a.connections.get(e).add(n),r.connections.has(e)||r.connections.set(e,new Set),r.connections.get(e).add(t),r.connections.get(e).size>this.config.M&&this.pruneConnections(r,e))}if(r.size>0){const[e,t]=[...r][0];if(t<i){i=t;const n=this.nouns.get(e);n?o=n:console.error(`Nearest noun with ID ${e} not found in addItem`)}}}return r>this.maxLevel&&(this.maxLevel=r,this.entryPointId=t),this.nouns.set(t,a),t}async search(e,t=10){if(0===this.nouns.size)return[];if(!e)throw new Error("Query vector is undefined or null");if(null!==this.dimension&&e.length!==this.dimension)throw new Error(`Query vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(!this.entryPointId)return console.error("Entry point ID is null"),[];const n=this.nouns.get(this.entryPointId);if(!n)return console.error(`Entry point with ID ${this.entryPointId} not found`),[];let r=n,a=this.distanceFunction(e,r.vector);for(let t=this.maxLevel;t>0;t--){let n=!0;for(;n;){n=!1;const s=r.connections.get(t)||new Set;if(this.useParallelization&&s.size>=10){const t=[];for(const e of s){const n=this.nouns.get(e);n&&t.push({id:e,vector:n.vector})}const o=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of o)if(t<a){a=t;const s=this.nouns.get(e);s&&(r=s,n=!0)}}else for(const t of s){const s=this.nouns.get(t);if(!s)continue;const o=this.distanceFunction(e,s.vector);o<a&&(a=o,r=s,n=!0)}}}return[...await this.searchLayer(e,r,Math.max(this.config.efSearch,t),0)].slice(0,t)}removeItem(e){if(!this.nouns.has(e))return!1;const t=this.nouns.get(e);for(const[n,r]of t.connections.entries())for(const t of r){const r=this.nouns.get(t);r&&(r.connections.has(n)&&(r.connections.get(n).delete(e),this.pruneConnections(r,n)))}for(const[t,n]of this.nouns.entries())if(t!==e)for(const[t,r]of n.connections.entries())r.has(e)&&(r.delete(e),this.pruneConnections(n,t));if(this.nouns.delete(e),this.entryPointId===e)if(0===this.nouns.size)this.entryPointId=null,this.maxLevel=0;else{let e=0,t=null;for(const[n,r]of this.nouns.entries()){if(0===r.connections.size)continue;const a=Math.max(...r.connections.keys());a>=e&&(e=a,t=n)}this.entryPointId=t,this.maxLevel=e}return!0}getNouns(){return new Map(this.nouns)}clear(){this.nouns.clear(),this.entryPointId=null,this.maxLevel=0}size(){return this.nouns.size}getDistanceFunction(){return this.distanceFunction}getEntryPointId(){return this.entryPointId}getMaxLevel(){return this.maxLevel}getDimension(){return this.dimension}getConfig(){return{...this.config}}async searchLayer(e,t,n,r){const a=new Set([t.id]),s=new Map;s.set(t.id,this.distanceFunction(e,t.vector));const o=new Map;for(o.set(t.id,this.distanceFunction(e,t.vector));s.size>0;){const[t,i]=[...s][0];s.delete(t);const c=[...o][o.size-1];if(o.size>=n&&i>c[1])break;const u=this.nouns.get(t);if(!u){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const l=u.connections.get(r)||new Set;if(this.useParallelization&&l.size>=10){const t=[];for(const e of l)if(!a.has(e)){a.add(e);const n=this.nouns.get(e);if(!n)continue;t.push({id:e,vector:n.vector})}if(t.length>0){const r=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of r)if((o.size<n||t<c[1])&&(s.set(e,t),o.set(e,t),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}else for(const t of l)if(!a.has(t)){a.add(t);const r=this.nouns.get(t);if(!r)continue;const i=this.distanceFunction(e,r.vector);if((o.size<n||i<c[1])&&(s.set(t,i),o.set(t,i),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}return new Map([...o].sort((e,t)=>e[1]-t[1]))}selectNeighbors(e,t,n){if(t.size<=n)return t;const r=[...t].sort((e,t)=>e[1]-t[1]),a=new Map;for(let e=0;e<Math.min(n,r.length);e++)a.set(r[e][0],r[e][1]);return a}pruneConnections(e,t){const n=e.connections.get(t);if(n.size<=this.config.M)return;const r=new Map,a=new Set;for(const t of n){const n=this.nouns.get(t);n&&(r.set(t,this.distanceFunction(e.vector,n.vector)),a.add(t))}if(0===r.size)return void e.connections.set(t,new Set);const s=this.selectNeighbors(e.vector,r,this.config.M);e.connections.set(t,new Set(s.keys()))}getRandomLevel(){const e=Math.random();return Math.floor(-Math.log(e)*(1/Math.log(this.config.M)))}}const j={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class q{constructor(e=16,t=256){this.centroids=[],this.subvectorSize=0,this.initialized=!1,this.dimension=0,this.numSubvectors=e,this.numCentroids=t}train(e){if(0===e.length)throw new Error("Cannot train product quantizer with empty vector set");this.dimension=e[0].length,this.subvectorSize=Math.ceil(this.dimension/this.numSubvectors);for(let t=0;t<this.numSubvectors;t++){const n=e.map(e=>{const n=t*this.subvectorSize,r=Math.min(n+this.subvectorSize,this.dimension);return e.slice(n,r)});this.centroids[t]=this.kMeansPlusPlus(n,this.numCentroids)}this.initialized=!0}quantize(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=n*this.subvectorSize,a=Math.min(r+this.subvectorSize,this.dimension),s=e.slice(r,a);let o=Number.MAX_VALUE,i=0;for(let e=0;e<this.centroids[n].length;e++){const t=this.centroids[n][e],r=this.euclideanDistanceSquared(s,t);r<o&&(o=r,i=e)}t.push(i)}return t}reconstruct(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.numSubvectors)throw new Error(`Code length mismatch: expected ${this.numSubvectors}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=e[n],a=this.centroids[n][r];for(const e of a)t.push(e)}return t.slice(0,this.dimension)}euclideanDistanceSquared(e,t){let n=0;const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a]-t[a];n+=r*r}return n}kMeansPlusPlus(e,t){if(e.length<t)return[...e];const n=[],r=Math.floor(Math.random()*e.length);n.push([...e[r]]);for(let r=1;r<t;r++){const t=e.map(e=>{let t=Number.MAX_VALUE;for(const r of n){const n=this.euclideanDistanceSquared(e,r);t=Math.min(t,n)}return t}),r=t.reduce((e,t)=>e+t,0);let a=Math.random()*r,s=0;for(let e=0;e<t.length;e++)if(a-=t[e],a<=0){s=e;break}n.push([...e[s]])}return n}getCentroids(){return this.centroids}setCentroids(e){this.centroids=e,this.numSubvectors=e.length,this.numCentroids=e[0].length,this.initialized=!0}getDimension(){return this.dimension}setDimension(e){this.dimension=e,this.subvectorSize=Math.ceil(e/this.numSubvectors)}}class K extends H{constructor(e={},t,n=null){super(e,t),this.productQuantizer=null,this.storage=null,this.useDiskBasedIndex=!1,this.useProductQuantization=!1,this.quantizedVectors=new Map,this.memoryUsage=0,this.vectorCount=0,this.optimizedConfig={...j,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new q(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.useDiskBasedIndex=this.optimizedConfig.useDiskBasedIndex||!1}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");const r=8*n.length+this.optimizedConfig.M*this.optimizedConfig.ml*16;if(this.memoryUsage+=r,this.vectorCount++,this.useProductQuantization&&this.memoryUsage>this.optimizedConfig.memoryThreshold&&this.productQuantizer&&!this.productQuantizer.getDimension()&&this.initializeProductQuantizer(),this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const e=this.productQuantizer.quantize(n);this.quantizedVectors.set(t,e);const r=this.productQuantizer.reconstruct(e);return await super.addItem({id:t,vector:r})}if(this.useDiskBasedIndex&&this.storage){const e={id:t,vector:n,connections:new Map};this.storage.saveNoun(e).catch(e=>{console.error(`Failed to save noun ${t} to storage:`,e)})}return await super.addItem(e)}async search(e,t=10){if(!e)throw new Error("Query vector is undefined or null");if(this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const n=this.productQuantizer.quantize(e),r=this.productQuantizer.reconstruct(n);return await super.search(r,t)}return await super.search(e,t)}removeItem(e){return this.useProductQuantization&&this.quantizedVectors.delete(e),this.useDiskBasedIndex&&this.storage&&this.storage.deleteNoun(e).catch(t=>{console.error(`Failed to delete noun ${e} from storage:`,t)}),this.vectorCount>0&&(this.memoryUsage=Math.max(0,this.memoryUsage-this.memoryUsage/this.vectorCount),this.vectorCount--),super.removeItem(e)}clear(){this.useProductQuantization&&(this.quantizedVectors.clear(),this.productQuantizer=new q(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.memoryUsage=0,this.vectorCount=0,super.clear()}initializeProductQuantizer(){if(!this.productQuantizer)return;const e=super.getNouns(),t=[];for(const[n,r]of e)t.push(r.vector);if(t.length>0){this.productQuantizer.train(t);for(const[t,n]of e){const e=this.productQuantizer.quantize(n.vector);this.quantizedVectors.set(t,e)}console.log(`Initialized product quantizer with ${t.length} vectors`)}}getProductQuantizer(){return this.productQuantizer}getOptimizedConfig(){return{...this.optimizedConfig}}getMemoryUsage(){return this.memoryUsage}setStorage(e){this.storage=e}getStorage(){return this.storage}setUseDiskBasedIndex(e){this.useDiskBasedIndex=e}getUseDiskBasedIndex(){return this.useDiskBasedIndex}setUseProductQuantization(e){this.useProductQuantization=e}getUseProductQuantization(){return this.useProductQuantization}}const X="nouns",Y="verbs",Q="metadata",J="person",Z="place",ee="thing",te="event",ne="concept",re="content",ae="default";class se{constructor(){this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.personDir=null,this.placeDir=null,this.thingDir=null,this.eventDir=null,this.conceptDir=null,this.contentDir=null,this.defaultDir=null,this.isInitialized=!1,this.isAvailable=!1,this.isPersistentRequested=!1,this.isPersistentGranted=!1,this.isAvailable="undefined"!=typeof navigator&&"storage"in navigator&&"getDirectory"in navigator.storage}async init(){if(!this.isInitialized){if(!this.isAvailable)throw new Error("Origin Private File System is not available in this environment");try{const e=await navigator.storage.getDirectory();this.rootDir=await e.getDirectoryHandle("opfs-vector-db",{create:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(X,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(Y,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(Q,{create:!0}),this.personDir=await this.nounsDir.getDirectoryHandle(J,{create:!0}),this.placeDir=await this.nounsDir.getDirectoryHandle(Z,{create:!0}),this.thingDir=await this.nounsDir.getDirectoryHandle(ee,{create:!0}),this.eventDir=await this.nounsDir.getDirectoryHandle(te,{create:!0}),this.conceptDir=await this.nounsDir.getDirectoryHandle(ne,{create:!0}),this.contentDir=await this.nounsDir.getDirectoryHandle(re,{create:!0}),this.defaultDir=await this.nounsDir.getDirectoryHandle(ae,{create:!0}),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize OPFS storage:",e),new Error(`Failed to initialize OPFS storage: ${e}`)}}}isOPFSAvailable(){return this.isAvailable}async requestPersistentStorage(){if(!this.isAvailable)return console.warn("Cannot request persistent storage: OPFS is not available"),!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted||(this.isPersistentGranted=await navigator.storage.persist()),this.isPersistentRequested=!0,this.isPersistentGranted}catch(e){return console.warn("Failed to request persistent storage:",e),!1}}async isPersistent(){if(!this.isAvailable)return!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted}catch(e){return console.warn("Failed to check persistent storage status:",e),!1}}async saveNoun(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodeDirectory(e.id),r=await n.getFileHandle(e.id,{create:!0}),a=await r.createWritable();await a.write(JSON.stringify(t)),await a.close()}catch(t){throw console.error(`Failed to save noun ${e.id}:`,t),new Error(`Failed to save noun ${e.id}: ${t}`)}}async getNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e);try{const n=await t.getFileHandle(e),r=await n.getFile(),a=await r.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch(n){if(t!==this.defaultDir)try{const t=await this.defaultDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(n){const r=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const n of r)if(n!==t)try{const t=await n.getFileHandle(e),r=await t.getFile(),a=await r.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch{}return null}return null}}catch(t){throw console.error(`Failed to get node ${e}:`,t),new Error(`Failed to get node ${e}: ${t}`)}}async getNounsByNounType(e){await this.ensureInitialized();try{const t=[];let n;switch(e){case"person":n=this.personDir;break;case"place":n=this.placeDir;break;case"thing":n=this.thingDir;break;case"event":n=this.eventDir;break;case"concept":n=this.conceptDir;break;case"content":n=this.contentDir;break;default:n=this.defaultDir}try{const e=n.entries();for await(const[n,r]of e)try{if("file"!==r.kind)continue;const e=r,n=await e.getFile(),a=await n.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));t.push({id:s.id,vector:s.vector,connections:o})}catch(e){console.warn(`Failed to read node ${n} from directory:`,e)}}catch(t){console.warn(`Failed to read directory for noun type ${e}:`,t)}return t}catch(t){throw console.error(`Failed to get nouns for noun type ${e}:`,t),new Error(`Failed to get nouns for noun type ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNounsByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async deleteNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e);try{return void await t.removeEntry(e)}catch(n){if(t!==this.defaultDir)try{return void await this.defaultDir.removeEntry(e)}catch(n){const r=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const n of r)if(n!==t)try{return void await n.removeEntry(e)}catch{}return}return}}catch(t){throw console.error(`Failed to delete noun ${e}:`,t),new Error(`Failed to delete noun ${e}: ${t}`)}}async saveVerb(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.verbsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save verb ${e.id}:`,t),new Error(`Failed to save verb ${e.id}: ${t}`)}}async getVerb(e){await this.ensureInitialized();try{const t=await this.verbsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch(t){if("NotFoundError"===t.name)return null;throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllEdges(){await this.ensureInitialized();try{const e=[],t=this.verbsDir.entries();for await(const[n,r]of t){if("file"!==r.kind)continue;const t=await this.getVerb(n);t&&e.push(t)}return e}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getAllVerbs(){return this.getAllEdges()}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async deleteVerb(e){return this.deleteEdge(e)}async getEdgesBySource(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getEdgesByTarget(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getEdgesByType(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async getVerbsByType(e){return this.getEdgesByType(e)}async saveMetadata(e,t){await this.ensureInitialized();try{const n=await this.metadataDir.getFileHandle(e,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=await this.metadataDir.getFileHandle(e),n=await t.getFile(),r=await n.text();return JSON.parse(r)}catch(t){if("NotFoundError"===t.name)return null;throw console.error(`Failed to get metadata for ${e}:`,t),new Error(`Failed to get metadata for ${e}: ${t}`)}}async clear(){await this.ensureInitialized();try{await this.rootDir.removeEntry(X,{recursive:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(X,{create:!0}),this.personDir=await this.nounsDir.getDirectoryHandle(J,{create:!0}),this.placeDir=await this.nounsDir.getDirectoryHandle(Z,{create:!0}),this.thingDir=await this.nounsDir.getDirectoryHandle(ee,{create:!0}),this.eventDir=await this.nounsDir.getDirectoryHandle(te,{create:!0}),this.conceptDir=await this.nounsDir.getDirectoryHandle(ne,{create:!0}),this.contentDir=await this.nounsDir.getDirectoryHandle(re,{create:!0}),this.defaultDir=await this.nounsDir.getDirectoryHandle(ae,{create:!0}),await this.rootDir.removeEntry(Y,{recursive:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(Y,{create:!0}),await this.rootDir.removeEntry(Q,{recursive:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(Q,{create:!0})}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async ensureInitialized(){this.isInitialized||await this.init()}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}async getNodeDirectory(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return this.personDir;case"place":return this.placeDir;case"thing":return this.thingDir;case"event":return this.eventDir;case"concept":return this.conceptDir;case"content":return this.contentDir;default:return this.defaultDir}return this.defaultDir}catch(e){return this.defaultDir}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{for await(const[r,a]of e.entries())if("file"===a.kind){n+=(await a.getFile()).size}else"directory"===a.kind&&(n+=await t(a))}catch(e){console.warn("Error calculating size for directory:",e)}return n},n=async e=>{let t=0;try{for await(const[n,r]of e.entries())"file"===r.kind&&t++}catch(e){console.warn("Error counting files in directory:",e)}return t};this.nounsDir&&(e+=await t(this.nounsDir)),this.verbsDir&&(e+=await t(this.verbsDir)),this.metadataDir&&(e+=await t(this.metadataDir));const r=this.personDir?await t(this.personDir):0,a=this.placeDir?await t(this.placeDir):0,s=this.thingDir?await t(this.thingDir):0,o=this.eventDir?await t(this.eventDir):0,i=this.conceptDir?await t(this.conceptDir):0,c=this.contentDir?await t(this.contentDir):0,u=this.defaultDir?await t(this.defaultDir):0;let l=null,d={isPersistent:await this.isPersistent(),nounTypes:{person:{size:r,count:this.personDir?await n(this.personDir):0},place:{size:a,count:this.placeDir?await n(this.placeDir):0},thing:{size:s,count:this.thingDir?await n(this.thingDir):0},event:{size:o,count:this.eventDir?await n(this.eventDir):0},concept:{size:i,count:this.conceptDir?await n(this.conceptDir):0},content:{size:c,count:this.contentDir?await n(this.contentDir):0},default:{size:u,count:this.defaultDir?await n(this.defaultDir):0}}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();l=e.quota||null,d={...d,usage:e.usage,quota:e.quota,freePercentage:e.quota?(e.quota-(e.usage||0))/e.quota*100:null}}}catch(e){console.warn("Unable to get storage estimate:",e)}return{type:"opfs",used:e,quota:l,details:d}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}}class oe{constructor(){this.nouns=new Map,this.verbs=new Map,this.metadata=new Map,this.nouns.set(J,new Map),this.nouns.set(Z,new Map),this.nouns.set(ee,new Map),this.nouns.set(te,new Map),this.nouns.set(ne,new Map),this.nouns.set(re,new Map),this.nouns.set(ae,new Map)}async saveNoun(e){return this.saveNode(e)}async getNoun(e){return this.getNode(e)}async getAllNouns(){return this.getAllNodes()}async getNounsByNounType(e){return this.getNodesByNounType(e)}async deleteNoun(e){return this.deleteNode(e)}async saveVerb(e){return this.saveEdge(e)}async getVerb(e){return this.getEdge(e)}async getAllVerbs(){return this.getAllEdges()}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getVerbsByType(e){return this.getEdgesByType(e)}async deleteVerb(e){return this.deleteEdge(e)}async init(){}async getNodeType(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return J;case"place":return Z;case"thing":return ee;case"event":return te;case"concept":return ne;case"content":return re;default:return ae}return ae}catch(e){return ae}}async saveNode(e){const t={id:e.id,vector:[...e.vector],connections:new Map};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));const n=await this.getNodeType(e.id);this.nouns.get(n).set(e.id,t)}async getNode(e){const t=await this.getNodeType(e);let n=this.nouns.get(t).get(e);if(!n){if(t!==ae){if(n=this.nouns.get(ae).get(e),!n){const r=[J,Z,ee,te,ne,re];for(const a of r){if(a===t)continue;if(n=this.nouns.get(a).get(e),n)break}}}if(!n)return null}const r={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,t]of n.connections.entries())r.connections.set(e,new Set(t));return r}async getNodesByNounType(e){const t=[];let n;switch(e){case"person":n=this.nouns.get(J);break;case"place":n=this.nouns.get(Z);break;case"thing":n=this.nouns.get(ee);break;case"event":n=this.nouns.get(te);break;case"concept":n=this.nouns.get(ne);break;case"content":n=this.nouns.get(re);break;default:n=this.nouns.get(ae)}for(const e of n.keys()){const n=await this.getNode(e);n&&t.push(n)}return t}async getAllNodes(){const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNodesByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}async deleteNode(e){const t=await this.getNodeType(e);if(!this.nouns.get(t).delete(e)&&t!==ae){if(!this.nouns.get(ae).delete(e)){const n=[J,Z,ee,te,ne,re];for(const r of n){if(r===t)continue;if(this.nouns.get(r).delete(e))break}}}}async saveMetadata(e,t){this.metadata.set(e,JSON.parse(JSON.stringify(t)))}async getMetadata(e){const t=this.metadata.get(e);return t?JSON.parse(JSON.stringify(t)):null}async saveEdge(e){const t={id:e.id,vector:[...e.vector],connections:new Map,sourceId:e.sourceId,targetId:e.targetId,type:e.type,weight:e.weight,metadata:e.metadata?JSON.parse(JSON.stringify(e.metadata)):void 0};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.verbs.set(e.id,t)}async getEdge(e){const t=this.verbs.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map,sourceId:t.sourceId,targetId:t.targetId,type:t.type,weight:t.weight,metadata:t.metadata?JSON.parse(JSON.stringify(t.metadata)):void 0};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllEdges(){const e=[];for(const t of this.verbs.keys()){const n=await this.getEdge(t);n&&e.push(n)}return e}async getEdgesBySource(e){const t=[];for(const n of this.verbs.values())if(n.sourceId===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async getEdgesByTarget(e){const t=[];for(const n of this.verbs.values())if(n.targetId===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async getEdgesByType(e){const t=[];for(const n of this.verbs.values())if(n.type===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async deleteEdge(e){this.verbs.delete(e)}async clear(){const e=[J,Z,ee,te,ne,re,ae];for(const t of e){this.nouns.get(t).clear()}this.verbs.clear(),this.metadata.clear()}async getStorageStatus(){try{let e=0;const t=e=>{if(null==e)return 0;const n=typeof e;if("number"===n)return 8;if("string"===n)return 2*e.length;if("boolean"===n)return 4;if(Array.isArray(e))return e.reduce((e,n)=>e+t(n),0);if("object"===n){if(e instanceof Map){let n=0;for(const[r,a]of e.entries())n+=t(r)+t(a);return n}if(e instanceof Set){let n=0;for(const r of e)n+=t(r);return n}return Object.entries(e).reduce((e,[n,r])=>e+2*n.length+t(r),0)}return 0},n={},r=[J,Z,ee,te,ne,re,ae];let a=0,s=0;for(const e of r){const r=this.nouns.get(e);let o=0;for(const e of r.values())o+=t(e);n[e]={size:o,count:r.size},s+=o,a+=r.size}e+=s;let o=0;for(const e of this.verbs.values())o+=t(e);e+=o;let i=0;for(const e of this.metadata.values())i+=t(e);e+=i;let c=null,u={nodeCount:a,edgeCount:this.verbs.size,metadataCount:this.metadata.size,nounTypes:n,nodesSize:s,edgesSize:o,metadataSize:i};if("undefined"!=typeof window&&window.performance&&window.performance.memory){const e=window.performance.memory;c=e.jsHeapSizeLimit,u={...u,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}return{type:"memory",used:e,quota:c,details:u}}catch(e){return console.error("Failed to get memory storage status:",e),{type:"memory",used:0,quota:null,details:{error:String(e)}}}}}async function ie(e={}){const t="undefined"!=typeof window,n="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;"undefined"!=typeof window||"undefined"!=typeof process&&process.versions&&process.versions.node;if(e.forceMemoryStorage)return console.log("Using in-memory storage (forced by configuration)"),new oe;const r={bucketName:void 0,accountId:void 0,accessKeyId:void 0,secretAccessKey:void 0,region:void 0,endpoint:void 0};if(e.r2Storage||e.s3Storage||e.gcsStorage||e.customS3Storage||n&&(process.env.R2_BUCKET_NAME||process.env.S3_BUCKET_NAME||process.env.GCS_BUCKET_NAME))try{const t=n?{bucketName:process.env.R2_BUCKET_NAME,accountId:process.env.R2_ACCOUNT_ID,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY}:r,a=n?{bucketName:process.env.S3_BUCKET_NAME,accessKeyId:process.env.S3_ACCESS_KEY_ID||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY||process.env.AWS_SECRET_ACCESS_KEY,region:process.env.S3_REGION||process.env.AWS_REGION}:r,s=n?{bucketName:process.env.GCS_BUCKET_NAME,accessKeyId:process.env.GCS_ACCESS_KEY_ID,secretAccessKey:process.env.GCS_SECRET_ACCESS_KEY,endpoint:process.env.GCS_ENDPOINT}:r,o={...e,r2Storage:e.r2Storage?{...t,...e.r2Storage}:t.bucketName&&t.accessKeyId&&t.secretAccessKey?t:void 0,s3Storage:e.s3Storage?{...a,...e.s3Storage}:a.bucketName&&a.accessKeyId&&a.secretAccessKey?a:void 0,gcsStorage:e.gcsStorage?{...s,...e.gcsStorage}:s.bucketName&&s.accessKeyId&&s.secretAccessKey?s:void 0},i=await Promise.resolve().then(function(){return Fe});if(o.r2Storage&&o.r2Storage.bucketName&&o.r2Storage.accountId&&o.r2Storage.accessKeyId&&o.r2Storage.secretAccessKey)return console.log("Using Cloudflare R2 storage"),new i.R2Storage({bucketName:o.r2Storage.bucketName,accountId:o.r2Storage.accountId,accessKeyId:o.r2Storage.accessKeyId,secretAccessKey:o.r2Storage.secretAccessKey,serviceType:"r2"});if(o.s3Storage&&o.s3Storage.bucketName&&o.s3Storage.accessKeyId&&o.s3Storage.secretAccessKey)return console.log("Using Amazon S3 storage"),new i.S3CompatibleStorage({bucketName:o.s3Storage.bucketName,accessKeyId:o.s3Storage.accessKeyId,secretAccessKey:o.s3Storage.secretAccessKey,region:o.s3Storage.region,serviceType:"s3"});if(o.gcsStorage&&o.gcsStorage.bucketName&&o.gcsStorage.accessKeyId&&o.gcsStorage.secretAccessKey)return console.log("Using Google Cloud Storage"),new i.S3CompatibleStorage({bucketName:o.gcsStorage.bucketName,accessKeyId:o.gcsStorage.accessKeyId,secretAccessKey:o.gcsStorage.secretAccessKey,endpoint:o.gcsStorage.endpoint,serviceType:"gcs"});if(o.customS3Storage&&o.customS3Storage.bucketName&&o.customS3Storage.accessKeyId&&o.customS3Storage.secretAccessKey)return console.log("Using custom S3-compatible storage"),new i.S3CompatibleStorage({bucketName:o.customS3Storage.bucketName,accessKeyId:o.customS3Storage.accessKeyId,secretAccessKey:o.customS3Storage.secretAccessKey,endpoint:o.customS3Storage.endpoint,region:o.customS3Storage.region,serviceType:"custom"})}catch(e){console.warn("Failed to load S3CompatibleStorage, falling back to environment-specific storage:",e)}if(t){if(!e.forceFileSystemStorage)try{const t=new se;if(t.isOPFSAvailable()){if(e.requestPersistentStorage){await t.requestPersistentStorage()?console.log("Persistent storage permission granted"):console.warn("Persistent storage permission denied")}return console.log("Using Origin Private File System (OPFS) storage"),t}}catch(e){console.warn("OPFS storage initialization failed:",e)}return console.log("Using in-memory storage for browser environment"),new oe}if(!n)return console.log("Using in-memory storage for serverless/unknown environment"),new oe;try{const e=await Promise.resolve().then(function(){return ke});return console.log("Using file system storage for Node.js environment"),new e.FileSystemStorage}catch(e){return console.warn("Failed to load FileSystemStorage:",e),console.log("Using in-memory storage for Node.js environment"),new oe}}const ce={Person:"person",Place:"place",Thing:"thing",Event:"event",Concept:"concept",Content:"content",Group:"group",List:"list",Category:"category"},ue={AttributedTo:"attributedTo",Controls:"controls",Created:"created",Earned:"earned",Owns:"owns",MemberOf:"memberOf",RelatedTo:"relatedTo",WorksWith:"worksWith",FriendOf:"friendOf",ReportsTo:"reportsTo",Supervises:"supervises",Mentors:"mentors",Follows:"follows",Likes:"likes"};var le;!function(e){e.SENSE="sense",e.CONDUIT="conduit",e.COGNITION="cognition",e.MEMORY="memory",e.PERCEPTION="perception",e.DIALOG="dialog",e.ACTIVATION="activation",e.WEBSOCKET="webSocket"}(le||(le={}));class de{constructor(e){this.description="Base conduit augmentation",this.enabled=!0,this.isInitialized=!1,this.connections=new Map,this.name=e}async initialize(){if(!this.isInitialized)try{this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){for(const[e,t]of this.connections.entries())try{t.close&&await t.close()}catch(t){console.error(`Failed to close connection ${e}:`,t)}this.connections.clear(),this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}class he extends de{constructor(e="websocket-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebSockets",this.webSocketConnections=new Map,this.messageCallbacks=new Map}getType(){return le.CONDUIT}async establishConnection(e,t){await this.ensureInitialized();try{const n=e,r=t.protocols,a=await this.connectWebSocket(n,r);return this.connections.set(a.connectionId,a),{success:!0,data:a}}catch(t){return console.error(`Failed to establish connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish connection: ${t}`}}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=v(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`WebSocket connection ${e} not found`);if(!n.send)throw new Error(`WebSocket connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`WebSocket connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`WebSocket connection ${e} not found`);if(!r.close)throw new Error(`WebSocket connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}class pe extends de{constructor(e="webrtc-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebRTC",this.peerConnections=new Map,this.dataChannels=new Map,this.webSocketConnections=new Map,this.messageCallbacks=new Map,this.signalServer=null}getType(){return le.CONDUIT}async initialize(){if(!this.isInitialized)try{if("undefined"==typeof RTCPeerConnection)throw new Error("WebRTC is not available in this environment");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async establishConnection(e,t){await this.ensureInitialized();try{!this.signalServer&&t.signalServerUrl&&(this.signalServer=await this.connectWebSocket(t.signalServerUrl),await this.onWebSocketMessage(this.signalServer.connectionId,async e=>{const n=e;if("ice-candidate"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.addIceCandidate(new RTCIceCandidate(n.candidate))}catch(e){console.error("Failed to add ICE candidate:",e)}}else if("offer"===n.type&&n.targetPeerId===t.localPeerId)await this.handleOffer(n.sourcePeerId,n.offer,t);else if("answer"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.setRemoteDescription(new RTCSessionDescription(n.answer))}catch(e){console.error("Failed to set remote description:",e)}}}));const n=new RTCPeerConnection({iceServers:t.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),r=v();this.peerConnections.set(e,n);const a=n.createDataChannel("brainy-sync",{ordered:!0});a.onopen=()=>{console.log(`Data channel to ${e} opened`)},a.onclose=()=>{console.log(`Data channel to ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},a.onerror=e=>{console.error("Data channel error:",e)};const s=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}s(t)}catch(e){console.error("Error handling WebRTC message:",e)}},this.dataChannels.set(e,a),n.onicecandidate=n=>{n.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:t.localPeerId,targetPeerId:e,candidate:n.candidate})};const o={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async t=>{const n=this.dataChannels.get(e);if(!n||"open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof t||t instanceof Blob?n.send(t):t instanceof ArrayBuffer?n.send(new Uint8Array(t)):ArrayBuffer.isView(t)?n.send(t):n.send(JSON.stringify(t))},close:async()=>{const t=this.dataChannels.get(e);t&&t.close();const n=this.peerConnections.get(e);n&&n.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:s};this.webSocketConnections.set(r,o),this.messageCallbacks.set(r,new Set);const i=await n.createOffer();return await n.setLocalDescription(i),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"offer",sourcePeerId:t.localPeerId,targetPeerId:e,offer:i}),{success:!0,data:o}}catch(t){return console.error(`Failed to establish WebRTC connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish WebRTC connection: ${t}`}}}async handleOffer(e,t,n){try{let r=this.peerConnections.get(e);r||(r=new RTCPeerConnection({iceServers:n.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),this.peerConnections.set(e,r),r.onicecandidate=t=>{t.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:n.localPeerId,targetPeerId:e,candidate:t.candidate})},r.ondatachannel=t=>{const n=t.channel,r=v();this.dataChannels.set(e,n),n.onopen=()=>{console.log(`Data channel from ${e} opened`)},n.onclose=()=>{console.log(`Data channel from ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},n.onerror=e=>{console.error("Data channel error:",e)};const a=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};n.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}a(t)}catch(e){console.error("Error handling WebRTC message:",e)}};const s={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async e=>{if("open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof e||e instanceof Blob?n.send(e):e instanceof ArrayBuffer?n.send(new Uint8Array(e)):ArrayBuffer.isView(e)?n.send(e):n.send(JSON.stringify(e))},close:async()=>{n.close();const t=this.peerConnections.get(e);t&&t.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:a};this.webSocketConnections.set(r,s),this.messageCallbacks.set(r,new Set)}),await r.setRemoteDescription(new RTCSessionDescription(t));const a=await r.createAnswer();await r.setLocalDescription(a),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"answer",sourcePeerId:n.localPeerId,targetPeerId:e,answer:a})}catch(e){throw console.error("Failed to handle WebRTC offer:",e),new Error(`Failed to handle WebRTC offer: ${e}`)}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=v(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`Connection ${e} not found`);if(!n.send)throw new Error(`Connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`Connection ${e} not found`);if(!r.close)throw new Error(`Connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}async function fe(e,t,n={}){switch(e){case"websocket":const n=new he(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new pe(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class me extends he{constructor(e="server-search-conduit"){super(e),this.localDb=null}async initialize(){if(!this.isInitialized)try{if(await super.initialize(),!this.localDb)throw new Error("Local database not set. Call setLocalDb before initializing.");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}setLocalDb(e){this.localDb=e}getLocalDb(){return this.localDb}async searchServer(e,t,n=10){await this.ensureInitialized();try{const r=await this.readData({connectionId:e,query:{type:"search",query:t,limit:n}});if(r.success&&r.data){const e=r.data;if(this.localDb)for(const t of e){await this.localDb.get(t.id)||await this.localDb.add(t.vector,t.metadata)}return{success:!0,data:e}}return{success:!1,data:null,error:r.error||"Unknown error searching server"}}catch(e){return console.error("Error searching server:",e),{success:!1,data:null,error:`Error searching server: ${e}`}}}async searchLocal(e,t=10){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:null,error:"Local database not initialized"};return{success:!0,data:await this.localDb.searchText(e,t)}}catch(e){return console.error("Error searching local database:",e),{success:!1,data:null,error:`Error searching local database: ${e}`}}}async searchCombined(e,t,n=10){await this.ensureInitialized();try{const r=await this.searchLocal(t,n);if(!r.success)return r;const a=r.data;if(a.length>=n)return r;const s=await this.searchServer(e,t,n-a.length);if(!s.success)return r;const o=s.data,i=[...a],c=new Set(a.map(e=>e.id));for(const e of o)c.has(e.id)||i.push(e);return{success:!0,data:i}}catch(e){return console.error("Error performing combined search:",e),{success:!1,data:null,error:`Error performing combined search: ${e}`}}}async addToBoth(e,t,n={}){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:"",error:"Local database not initialized"};const r=await this.localDb.add(t,n),a=await this.localDb.get(r);if(!a)return{success:!1,data:"",error:"Failed to retrieve newly created noun"};const s=await this.writeData({connectionId:e,data:{type:"addNoun",vector:a.vector,metadata:a.metadata}});return s.success?{success:!0,data:r}:{success:!0,data:r,error:`Added locally but failed to add to server: ${s.error}`}}catch(e){return console.error("Error adding data to both:",e),{success:!1,data:"",error:`Error adding data to both: ${e}`}}}}class ge{constructor(e="server-search-activation"){this.enabled=!0,this.isInitialized=!1,this.conduitAugmentation=null,this.connections=new Map,this.name=e,this.description="Activation augmentation for server-hosted Brainy search"}getType(){return le.ACTIVATION}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}setConduitAugmentation(e){this.conduitAugmentation=e}storeConnection(e,t){this.connections.set(e,t)}getConnection(e){return this.connections.get(e)}triggerAction(e,t){if(!this.conduitAugmentation)return{success:!1,data:null,error:"Conduit augmentation not set"};switch(e){case"connectToServer":return this.handleConnectToServer(t||{});case"searchServer":return this.handleSearchServer(t||{});case"searchLocal":return this.handleSearchLocal(t||{});case"searchCombined":return this.handleSearchCombined(t||{});case"addToBoth":return this.handleAddToBoth(t||{});default:return{success:!1,data:null,error:`Unknown action: ${e}`}}}handleConnectToServer(e){const t=e.serverUrl,n=e.protocols;return t?{success:!0,data:this.conduitAugmentation.establishConnection(t,{protocols:n})}:{success:!1,data:null,error:"serverUrl parameter is required"}}handleSearchServer(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchServer(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleSearchLocal(e){const t=e.query,n=e.limit||10;return t?{success:!0,data:this.conduitAugmentation.searchLocal(t,n)}:{success:!1,data:null,error:"query parameter is required"}}handleSearchCombined(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchCombined(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleAddToBoth(e){const t=e.connectionId,n=e.data,r=e.metadata||{};return t?n?{success:!0,data:this.conduitAugmentation.addToBoth(t,n,r)}:{success:!1,data:null,error:"data parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}generateOutput(e,t){return{success:!1,data:"",error:"generateOutput is not implemented for ServerSearchActivationAugmentation"}}interactExternal(e,t){return{success:!1,data:null,error:"interactExternal is not implemented for ServerSearchActivationAugmentation"}}}async function ye(e,t={}){const n=new me(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new ge(t.activationName);await r.initialize(),r.setConduitAugmentation(n);const a=await n.establishConnection(e,{protocols:t.protocols});if(!a.success||!a.data)throw new Error(`Failed to connect to server: ${a.error}`);const s=a.data;return r.storeConnection(s.connectionId,s),{conduit:n,activation:r,connection:s}}class be{constructor(e={}){this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,this.distanceFunction=e.distanceFunction||I,e.hnswOptimized?(this.index=new K(e.hnswOptimized,this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0):this.index=new H(e.hnsw,this.distanceFunction),this.storage=e.storageAdapter||null,this.embeddingFunction=e.embeddingFunction||B,this.requestPersistentStorage=e.storage?.requestPersistentStorage||!1,this.readOnly=e.readOnly||!1,this.storageConfig=e.storage||{},e.remoteServer&&(this.remoteServerConfig=e.remoteServer)}checkReadOnly(){if(this.readOnly)throw new Error("Cannot perform write operation: database is in read-only mode")}async init(){if(!this.isInitialized&&!this.isInitializing){this.isInitializing=!0;try{try{console.log("Pre-loading Universal Sentence Encoder model..."),await this.embeddingFunction(""),console.log("Universal Sentence Encoder model loaded successfully")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e),console.log("Retrying Universal Sentence Encoder initialization...");try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return U}),t=e();await t(""),console.log("Successfully loaded Universal Sentence Encoder with fallback method"),this.embeddingFunction=t}catch(e){console.error("All attempts to load Universal Sentence Encoder failed:",e)}}if(!this.storage){const e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};this.storage=await ie(e)}await this.storage.init(),this.useOptimizedIndex&&this.index instanceof K&&this.index.setStorage(this.storage);const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)await this.index.addItem({id:t.id,vector:t.vector});if(this.remoteServerConfig&&this.remoteServerConfig.autoConnect)try{await this.connectToRemoteServer(this.remoteServerConfig.url,this.remoteServerConfig.protocols)}catch(e){console.warn("Failed to auto-connect to remote server:",e)}this.isInitialized=!0,this.isInitializing=!1}catch(e){throw console.error("Failed to initialize BrainyData:",e),this.isInitializing=!1,new Error(`Failed to initialize BrainyData: ${e}`)}}}async connectToRemoteServer(e,t){await this.ensureInitialized();try{const{conduit:n,connection:r}=await ye(e,{protocols:t,localDb:this});return this.serverSearchConduit=n,this.serverConnection=r,r}catch(e){throw console.error("Failed to connect to remote server:",e),new Error(`Failed to connect to remote server: ${e}`)}}async add(e,t,n={}){await this.ensureInitialized(),this.checkReadOnly();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize data: ${e}`)}if(!r)throw new Error("Vector is undefined or null");const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:v());await this.index.addItem({id:a,vector:r});const s=this.index.getNouns().get(a);if(!s)throw new Error(`Failed to retrieve newly created noun with ID ${a}`);if(await this.storage.saveNoun(s),void 0!==t){if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(ce).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ce.Concept)}await this.storage.saveMetadata(a,t)}if(n.addToRemote&&this.isConnectedToRemoteServer())try{await this.addToRemote(a,r,t)}catch(e){console.warn(`Failed to add to remote server: ${e}. Continuing with local add.`)}return a}catch(e){throw console.error("Failed to add vector:",e),new Error(`Failed to add vector: ${e}`)}}async addToBoth(e,t,n={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.add(e,t,{...n,addToRemote:!0})}async addToRemote(e,t,n){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const e=await this.serverSearchConduit.addToBoth(this.serverConnection.connectionId,t,n);if(!e.success)throw new Error(`Remote add failed: ${e.error}`);return!0}catch(e){throw console.error("Failed to add to remote server:",e),new Error(`Failed to add to remote server: ${e}`)}}async addBatch(e,t={}){await this.ensureInitialized(),this.checkReadOnly(),t.concurrency;const n=t.batchSize||50;try{const r=[],a=[...e];for(;a.length>0;){const e=a.splice(0,n),s=[],o=[];e.forEach((e,n)=>{if(Array.isArray(e.vectorOrData)&&e.vectorOrData.every(e=>"number"==typeof e)&&!t.forceEmbed)s.push({vectorOrData:e.vectorOrData,metadata:e.metadata,index:n});else if("string"==typeof e.vectorOrData)o.push({text:e.vectorOrData,metadata:e.metadata,index:n});else{const t=String(e.vectorOrData);o.push({text:t,metadata:e.metadata,index:n})}});const i=s.map(e=>this.add(e.vectorOrData,e.metadata,t));let c=[];if(o.length>0){const e=o.map(e=>e.text),n=await W(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const u=await Promise.all([...i,...c]);r.push(...u)}return r}catch(e){throw console.error("Failed to add batch of items:",e),new Error(`Failed to add batch of items: ${e}`)}}async addBatchToBoth(e,t={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.addBatch(e,{...t,addToRemote:!0})}async searchByNounTypes(e,t=10,n=null,r={}){await this.ensureInitialized();try{let a;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!r.forceEmbed)a=e;else try{a=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}if(!a)throw new Error("Query vector is undefined or null");if(n&&0!==n.length){const e=n.map(e=>this.storage.getNounsByNounType(e)),r=await Promise.all(e),s=[];for(const e of r)s.push(...e);const o=[];for(const e of s){const t=this.index.getDistanceFunction()(a,e.vector);o.push([e.id,t])}o.sort((e,t)=>e[1]-t[1]);const i=o.slice(0,t),c=[];for(const[e,t]of i){const n=s.find(t=>t.id===e);if(!n)continue;const r=await this.storage.getMetadata(e);c.push({id:e,score:t,vector:n.vector,metadata:r})}return c}{const e=await this.index.search(a,t),n=[];for(const[t,r]of e){const e=this.index.getNouns().get(t);if(!e)continue;const a=await this.storage.getMetadata(t);n.push({id:t,score:r,vector:e.vector,metadata:a})}return n}}catch(e){throw console.error("Failed to search vectors by noun types:",e),new Error(`Failed to search vectors by noun types: ${e}`)}}async search(e,t=10,n={}){if(n.searchVerbs){return(await this.searchVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes})).map(e=>({id:e.id,score:e.similarity,vector:e.embedding||[],metadata:{verb:e.verb,source:e.source,target:e.target,...e.data}}))}return n.searchConnectedNouns?this.searchNounsByVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes,direction:n.verbDirection}):"local"===n.searchMode?this.searchLocal(e,t,n):"remote"===n.searchMode?this.searchRemote(e,t,n):"combined"===n.searchMode?this.searchCombined(e,t,n):this.searchLocal(e,t,n)}async searchLocal(e,t=10,n={}){let r,a=e;if("string"!=typeof e||n.forceEmbed||(a=await this.embed(e),n.forceEmbed=!1),r=n.nounTypes&&n.nounTypes.length>0?await this.searchByNounTypes(a,t,n.nounTypes,{forceEmbed:n.forceEmbed}):await this.searchByNounTypes(a,t,null,{forceEmbed:n.forceEmbed}),n.includeVerbs&&this.storage)for(const e of r)try{const t=await this.storage.getVerbsBySource(e.id),n=await this.storage.getVerbsByTarget(e.id),r=[...t,...n];e.metadata||(e.metadata={}),e.metadata.associatedVerbs=r}catch(t){console.warn(`Failed to retrieve verbs for noun ${e.id}:`,t)}return r}async findSimilar(e,t={}){await this.ensureInitialized();const n=await this.get(e);if(!n)throw new Error(`Entity with ID ${e} not found`);const r=(t.limit||10)+1;return(await this.search(n.vector,r,{forceEmbed:!1,nounTypes:t.nounTypes,includeVerbs:t.includeVerbs,searchMode:t.searchMode})).filter(t=>t.id!==e).slice(0,t.limit||10)}async get(e){await this.ensureInitialized();try{const t=this.index.getNouns().get(e);if(!t)return null;const n=await this.storage.getMetadata(e);return{id:e,vector:t.vector,metadata:n}}catch(t){throw console.error(`Failed to get vector ${e}:`,t),new Error(`Failed to get vector ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=this.index.getNouns(),t=[];for(const[n,r]of e.entries()){const e=await this.storage.getMetadata(n);t.push({id:n,vector:r.vector,metadata:e})}return t}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async delete(e){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.removeItem(e))return!1;await this.storage.deleteNoun(e);try{await this.storage.saveMetadata(e,null)}catch(e){}return!0}catch(t){throw console.error(`Failed to delete vector ${e}:`,t),new Error(`Failed to delete vector ${e}: ${t}`)}}async updateMetadata(e,t){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.getNouns().get(e))return!1;if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(ce).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ce.Concept)}return await this.storage.saveMetadata(e,t),!0}catch(t){throw console.error(`Failed to update metadata for vector ${e}:`,t),new Error(`Failed to update metadata for vector ${e}: ${t}`)}}async relate(e,t,n,r){return this.addVerb(e,t,void 0,{type:n,metadata:r})}async addVerb(e,t,n,r={}){await this.ensureInitialized(),this.checkReadOnly();try{const a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a)throw new Error(`Source noun with ID ${e} not found`);if(!s)throw new Error(`Target noun with ID ${t} not found`);const o=r.id||v();let i;if(!r.metadata||n&&!r.forceEmbed)if(n)i=n;else{if(!a.vector||!s.vector||0===a.vector.length||0===s.vector.length||a.vector.length!==s.vector.length)throw new Error("Cannot average vectors: source or target vector is invalid or dimensions don't match");i=a.vector.map((e,t)=>(e+s.vector[t])/2)}else try{let e;e="string"==typeof r.metadata?r.metadata:r.metadata.description&&"string"==typeof r.metadata.description?r.metadata.description:JSON.stringify(r.metadata),"string"!=typeof e&&(e=String(e)),i=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize verb metadata: ${e}`)}let c=r.type;if(c){Object.values(ue).includes(c)||(console.warn(`Invalid verb type: ${c}. Using RelatedTo as default.`),c=ue.RelatedTo)}const u={id:o,vector:i,connections:new Map,sourceId:e,targetId:t,type:c,weight:r.weight,metadata:r.metadata};await this.index.addItem({id:o,vector:i});const l=this.index.getNouns().get(o);if(!l)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);return u.connections=l.connections,await this.storage.saveVerb(u),o}catch(e){throw console.error("Failed to add verb:",e),new Error(`Failed to add verb: ${e}`)}}async getVerb(e){await this.ensureInitialized();try{return await this.storage.getVerb(e)}catch(t){throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllVerbs(){await this.ensureInitialized();try{return await this.storage.getAllVerbs()}catch(e){throw console.error("Failed to get all verbs:",e),new Error(`Failed to get all verbs: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return await this.storage.getVerbsBySource(e)}catch(t){throw console.error(`Failed to get verbs by source ${e}:`,t),new Error(`Failed to get verbs by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return await this.storage.getVerbsByTarget(e)}catch(t){throw console.error(`Failed to get verbs by target ${e}:`,t),new Error(`Failed to get verbs by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return await this.storage.getVerbsByType(e)}catch(t){throw console.error(`Failed to get verbs by type ${e}:`,t),new Error(`Failed to get verbs by type ${e}: ${t}`)}}async deleteVerb(e){await this.ensureInitialized(),this.checkReadOnly();try{return!!this.index.removeItem(e)&&(await this.storage.deleteVerb(e),!0)}catch(t){throw console.error(`Failed to delete verb ${e}:`,t),new Error(`Failed to delete verb ${e}: ${t}`)}}async clear(){await this.ensureInitialized(),this.checkReadOnly();try{this.index.clear(),await this.storage.clear()}catch(e){throw console.error("Failed to clear vector database:",e),new Error(`Failed to clear vector database: ${e}`)}}size(){return this.index.size()}isReadOnly(){return this.readOnly}setReadOnly(e){this.readOnly=e}async embed(e){await this.ensureInitialized();try{return await this.embeddingFunction(e)}catch(e){throw console.error("Failed to embed data:",e),new Error(`Failed to embed data: ${e}`)}}async searchVerbs(e,t=10,n={}){await this.ensureInitialized();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}let a=[];if(n.verbTypes&&n.verbTypes.length>0){const e=n.verbTypes.map(e=>this.getVerbsByType(e)),t=await Promise.all(e);for(const e of t)a.push(...e)}else a=await this.storage.getAllVerbs();a=a.filter(e=>e.embedding&&e.embedding.length>0);const s=[];for(const e of a)if(e.embedding){const t=this.index.getDistanceFunction()(r,e.embedding);s.push({...e,similarity:t})}return s.sort((e,t)=>e.similarity-t.similarity),s.slice(0,t)}catch(e){throw console.error("Failed to search verbs:",e),new Error(`Failed to search verbs: ${e}`)}}async searchNounsByVerbs(e,t=10,n={}){await this.ensureInitialized();try{const r=await this.searchByNounTypes(e,2*t,null,{forceEmbed:n.forceEmbed});if(!n.verbTypes||0===n.verbTypes.length)return r.slice(0,t);const a=new Set,s=n.direction||"both";for(const e of r){let t=[];if("outgoing"===s||"both"===s){const n=await this.storage.getVerbsBySource(e.id);t.push(...n)}if("incoming"===s||"both"===s){const n=await this.storage.getVerbsByTarget(e.id);t.push(...n)}n.verbTypes&&n.verbTypes.length>0&&(t=t.filter(e=>e.verb&&n.verbTypes.includes(e.verb)));for(const n of t)n.source&&n.source!==e.id&&a.add(n.source),n.target&&n.target!==e.id&&a.add(n.target)}const o=[];for(const t of a)try{const r=this.index.getNouns().get(t);if(r){const a=await this.storage.getMetadata(t);let s;s=Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed?e:await this.embeddingFunction(e);const i=this.index.getDistanceFunction()(s,r.vector);o.push({id:t,score:i,vector:r.vector,metadata:a})}}catch(e){console.warn(`Failed to retrieve noun ${t}:`,e)}return o.sort((e,t)=>e.score-t.score),o.slice(0,t)}catch(e){throw console.error("Failed to search nouns by verbs:",e),new Error(`Failed to search nouns by verbs: ${e}`)}}async searchText(e,t=10,n={}){await this.ensureInitialized();try{const r=await this.embed(e);return await this.search(r,t,{nounTypes:n.nounTypes,includeVerbs:n.includeVerbs,searchMode:n.searchMode})}catch(e){throw console.error("Failed to search with text query:",e),new Error(`Failed to search with text query: ${e}`)}}async searchRemote(e,t=10,n={}){if(await this.ensureInitialized(),!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");try{let n;if(n="string"==typeof e?e:"vector-query",!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const r=await this.serverSearchConduit.searchServer(this.serverConnection.connectionId,n,t);if(!r.success)throw new Error(`Remote search failed: ${r.error}`);return r.data}catch(e){throw console.error("Failed to search remote server:",e),new Error(`Failed to search remote server: ${e}`)}}async searchCombined(e,t=10,n={}){if(await this.ensureInitialized(),!this.isConnectedToRemoteServer())return this.searchLocal(e,t,n);try{if(!1!==n.localFirst){const r=await this.searchLocal(e,t,n);if(r.length>=t)return r;const a=await this.searchRemote(e,t-r.length,{...n,storeResults:!0}),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}{const r=await this.searchRemote(e,t,{...n,storeResults:!0});if(r.length>=t)return r;const a=await this.searchLocal(e,t-r.length,n),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}}catch(e){throw console.error("Failed to perform combined search:",e),new Error(`Failed to perform combined search: ${e}`)}}isConnectedToRemoteServer(){return!(!this.serverSearchConduit||!this.serverConnection)}async disconnectFromRemoteServer(){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");return await this.serverSearchConduit.closeWebSocket(this.serverConnection.connectionId),this.serverSearchConduit=null,this.serverConnection=null,!0}catch(e){throw console.error("Failed to disconnect from remote server:",e),new Error(`Failed to disconnect from remote server: ${e}`)}}async ensureInitialized(){if(!this.isInitialized)if(this.isInitializing){let e=0;const t=100,n=50;for(;this.isInitializing&&!this.isInitialized&&e<t;)await new Promise(e=>setTimeout(e,n)),e++;this.isInitialized||await this.init()}else await this.init()}async status(){if(await this.ensureInitialized(),!this.storage)return{type:"any",used:0,quota:null,details:{error:"Storage not initialized"}};try{if("function"!=typeof this.storage.getStorageStatus){return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:"Storage adapter does not implement getStorageStatus method",storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}const e=await this.storage.getStorageStatus();let t={indexSize:this.size()};if(this.useOptimizedIndex&&this.index instanceof K){const e=this.index;t={...t,optimized:!0,memoryUsage:e.getMemoryUsage(),productQuantization:e.getUseProductQuantization(),diskBasedIndex:e.getUseDiskBasedIndex()}}else t.optimized=!1;return{type:e.type||"any",used:e.used||0,quota:e.quota||null,details:{...e.details||{},index:t}}}catch(e){console.error("Failed to get storage status:",e);return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:String(e),storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}}async shutDown(){try{this.isConnectedToRemoteServer()&&await this.disconnectFromRemoteServer(),_(),this.isInitialized=!1}catch(e){throw console.error("Failed to shut down BrainyData:",e),new Error(`Failed to shut down BrainyData: ${e}`)}}async backup(){await this.ensureInitialized();try{const e=await this.getAllNouns(),t=await this.getAllVerbs(),n=Object.values(ce),r=Object.values(ue),a={entryPointId:this.index.getEntryPointId(),maxLevel:this.index.getMaxLevel(),dimension:this.index.getDimension(),config:this.index.getConfig(),connections:{}},s=this.index.getNouns();for(const[e,t]of s.entries()){a.connections[e]={};for(const[n,r]of t.connections.entries())a.connections[e][n]=Array.from(r)}return{nouns:e,verbs:t,nounTypes:n,verbTypes:r,hnswIndex:a,version:"1.0.0"}}catch(e){throw console.error("Failed to backup data:",e),new Error(`Failed to backup data: ${e}`)}}async importSparseData(e,t={}){return this.restore(e,t)}async restore(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(t.clearExisting&&await this.clear(),!(e&&e.nouns&&e.verbs&&e.version))throw new Error("Invalid restore data format");e.nounTypes&&console.log(`Found ${e.nounTypes.length} noun types in restore data`),e.verbTypes&&console.log(`Found ${e.verbTypes.length} verb types in restore data`),e.hnswIndex&&console.log("Found HNSW index data in backup");let n=0;for(const t of e.nouns)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.add(t.vector,t.metadata,{id:t.id}),n++}catch(e){console.error(`Failed to restore noun ${t.id}:`,e)}let r=0;for(const t of e.verbs)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.addVerb(t.sourceId,t.targetId,t.vector,{id:t.id,type:t.metadata?.verb||ue.RelatedTo,metadata:t.metadata}),r++}catch(e){console.error(`Failed to restore verb ${t.id}:`,e)}if(e.hnswIndex&&n>0)try{console.log("Reconstructing HNSW index from backup data..."),this.index=new H(e.hnswIndex.config,this.distanceFunction);for(const t of e.nouns)t.vector&&t.vector.length>0&&await this.index.addItem({id:t.id,vector:t.vector});console.log("HNSW index reconstruction complete")}catch(e){console.error("Failed to reconstruct HNSW index:",e),console.log("Continuing with standard restore process...")}return{nounsRestored:n,verbsRestored:r}}catch(e){throw console.error("Failed to restore data:",e),new Error(`Failed to restore data: ${e}`)}}async generateRandomGraph(e={}){await this.ensureInitialized(),this.checkReadOnly();const t=e.nounCount||10,n=e.verbCount||20,r=e.nounTypes||Object.values(ce),a=e.verbTypes||Object.values(ue);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[ce.Person]:"A person with unique characteristics",[ce.Place]:"A location with specific attributes",[ce.Thing]:"An object with distinct properties",[ce.Event]:"An occurrence with temporal aspects",[ce.Concept]:"An abstract idea or notion",[ce.Content]:"A piece of content or information",[ce.Group]:"A collection of related entities",[ce.List]:"An ordered sequence of items",[ce.Category]:"A classification or grouping"};for(let n=0;n<t;n++){const t=r[Math.floor(Math.random()*r.length)],a={noun:t,label:`Random ${t} ${n+1}`,description:s[t]||`A random ${t}`,randomAttributes:{value:100*Math.random(),priority:Math.floor(5*Math.random())+1,tags:["tag-"+n%5,"category-"+n%3]}},o=await this.add(a.description,a);e.push(o)}const o=[],i={[ue.AttributedTo]:"Attribution relationship",[ue.Controls]:"Control relationship",[ue.Created]:"Creation relationship",[ue.Earned]:"Achievement relationship",[ue.Owns]:"Ownership relationship",[ue.MemberOf]:"Membership relationship",[ue.RelatedTo]:"General relationship",[ue.WorksWith]:"Collaboration relationship",[ue.FriendOf]:"Friendship relationship",[ue.ReportsTo]:"Reporting relationship",[ue.Supervises]:"Supervision relationship",[ue.Mentors]:"Mentorship relationship"};for(let t=0;t<n;t++){const n=Math.floor(Math.random()*e.length);let r=Math.floor(Math.random()*e.length);for(;r===n&&e.length>1;)r=Math.floor(Math.random()*e.length);const s=e[n],c=e[r],u=a[Math.floor(Math.random()*a.length)],l={verb:u,description:i[u]||`A random ${u} relationship`,weight:Math.random(),confidence:Math.random(),randomAttributes:{strength:100*Math.random(),duration:Math.floor(365*Math.random())+1,tags:["relation-"+t%5,"strength-"+t%3]}},d=await this.addVerb(s,c,void 0,{type:u,weight:l.weight,metadata:l});o.push(d)}return{nounIds:e,verbIds:o}}catch(e){throw console.error("Failed to generate random graph:",e),new Error(`Failed to generate random graph: ${e}`)}}}let xe,we;class ve{constructor(e){this.isInitialized=!1,this.rootDir=e||"",this.nounsDir="",this.verbsDir="",this.metadataDir="",this.personDir="",this.placeDir="",this.thingDir="",this.eventDir="",this.conceptDir="",this.contentDir="",this.defaultDir=""}async init(){if(!this.isInitialized)try{try{const e=await Promise.resolve().then(function(){return gF}),t=await Promise.resolve().then(function(){return yF});xe=e.default||e,we=t.default||t;const n=this.rootDir||process.cwd();this.rootDir=we.resolve(n,"brainy-data"),this.nounsDir=we.join(this.rootDir,"nouns"),this.verbsDir=we.join(this.rootDir,"verbs"),this.metadataDir=we.join(this.rootDir,"metadata"),this.personDir=we.join(this.nounsDir,"person"),this.placeDir=we.join(this.nounsDir,"place"),this.thingDir=we.join(this.nounsDir,"thing"),this.eventDir=we.join(this.nounsDir,"event"),this.conceptDir=we.join(this.nounsDir,"concept"),this.contentDir=we.join(this.nounsDir,"content"),this.defaultDir=we.join(this.nounsDir,"default")}catch(e){throw new Error(`Failed to import Node.js modules: ${e}. This adapter requires a Node.js environment.`)}await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.personDir),await this.ensureDirectoryExists(this.placeDir),await this.ensureDirectoryExists(this.thingDir),await this.ensureDirectoryExists(this.eventDir),await this.ensureDirectoryExists(this.conceptDir),await this.ensureDirectoryExists(this.contentDir),await this.ensureDirectoryExists(this.defaultDir),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize file system storage:",e),new Error(`Failed to initialize file system storage: ${e}`)}}async saveNoun(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodeDirectory(e.id),r=we.join(n,`${e.id}.json`);await xe.promises.writeFile(r,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e),n=we.join(t,`${e}.json`);try{await xe.promises.access(n)}catch{if(t!==this.defaultDir){const n=we.join(this.defaultDir,`${e}.json`);try{await xe.promises.access(n);const e=await xe.promises.readFile(n,"utf8"),t=JSON.parse(e),r=new Map;for(const[e,n]of Object.entries(t.connections))r.set(Number(e),new Set(n));return{id:t.id,vector:t.vector,connections:r}}catch{const n=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const r of n){if(r===t)continue;const n=we.join(r,`${e}.json`);try{await xe.promises.access(n);const e=await xe.promises.readFile(n,"utf8"),t=JSON.parse(e),r=new Map;for(const[e,n]of Object.entries(t.connections))r.set(Number(e),new Set(n));return{id:t.id,vector:t.vector,connections:r}}catch{}}return null}}return null}const r=await xe.promises.readFile(n,"utf8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(t){return console.error(`Failed to get node ${e}:`,t),null}}async getNounsByNounType(e){await this.ensureInitialized();try{let t;switch(e){case"person":t=this.personDir;break;case"place":t=this.placeDir;break;case"thing":t=this.thingDir;break;case"event":t=this.eventDir;break;case"concept":t=this.conceptDir;break;case"content":t=this.contentDir;break;default:t=this.defaultDir}const n=[];try{const e=(await xe.promises.readdir(t)).filter(e=>e.endsWith(".json")).map(e=>this.readNodeFromFile(we.join(t,e))),r=await Promise.all(e);n.push(...r.filter(e=>null!==e))}catch(t){console.warn(`Could not read directory for noun type ${e}:`,t)}return n}catch(t){throw console.error(`Failed to get nodes for noun type ${e}:`,t),new Error(`Failed to get nodes for noun type ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNounsByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nodes:",e),new Error(`Failed to get all nodes: ${e}`)}}async readNodeFromFile(e){try{const t=await xe.promises.readFile(e,"utf8"),n=JSON.parse(t),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r}}catch(t){return console.error(`Failed to read node from file ${e}:`,t),null}}async deleteNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e),n=we.join(t,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{if(t!==this.defaultDir){const n=we.join(this.defaultDir,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{const n=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const r of n){if(r===t)continue;const n=we.join(r,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{}}return}}return}}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveVerb(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=we.join(this.verbsDir,`${e.id}.json`);await xe.promises.writeFile(n,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb(e){await this.ensureInitialized();try{const t=we.join(this.verbsDir,`${e}.json`);try{await xe.promises.access(t)}catch{return null}const n=await xe.promises.readFile(t,"utf8"),r=JSON.parse(n),a=new Map;for(const[e,t]of Object.entries(r.connections))a.set(Number(e),new Set(t));return{id:r.id,vector:r.vector,connections:a,sourceId:r.sourceId,targetId:r.targetId,type:r.type,weight:r.weight,metadata:r.metadata}}catch(t){return console.error(`Failed to get edge ${e}:`,t),null}}async getAllVerbs(){await this.ensureInitialized();try{const e=(await xe.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).map(e=>{const t=we.basename(e,".json");return this.getVerb(t)});return(await Promise.all(e)).filter(e=>null!==e)}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async deleteVerb(e){await this.ensureInitialized();try{const t=we.join(this.verbsDir,`${e}.json`);try{await xe.promises.access(t)}catch{return}await xe.promises.unlink(t)}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{const n=we.join(this.metadataDir,`${e}.json`);await xe.promises.writeFile(n,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=we.join(this.metadataDir,`${e}.json`);try{await xe.promises.access(t)}catch{return null}const n=await xe.promises.readFile(t,"utf8");return JSON.parse(n)}catch(t){return console.error(`Failed to get metadata for ${e}:`,t),null}}async clear(){await this.ensureInitialized();try{await this.deleteDirectory(this.nounsDir),await this.deleteDirectory(this.verbsDir),await this.deleteDirectory(this.metadataDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.personDir),await this.ensureDirectoryExists(this.placeDir),await this.ensureDirectoryExists(this.thingDir),await this.ensureDirectoryExists(this.eventDir),await this.ensureDirectoryExists(this.conceptDir),await this.ensureDirectoryExists(this.contentDir),await this.ensureDirectoryExists(this.defaultDir)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async ensureInitialized(){this.isInitialized||await this.init()}async ensureDirectoryExists(e){try{await xe.promises.access(e)}catch{await xe.promises.mkdir(e,{recursive:!0})}}async deleteDirectory(e){try{const t=await xe.promises.readdir(e);for(const n of t){const t=we.join(e,n);(await xe.promises.stat(t)).isDirectory()?await this.deleteDirectory(t):await xe.promises.unlink(t)}await xe.promises.rmdir(e)}catch(e){if("ENOENT"!==e.code)throw e}}async countFilesInDirectory(e){try{return(await xe.promises.readdir(e)).filter(e=>e.endsWith(".json")).length}catch(e){if("ENOENT"===e.code)return 0;throw e}}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}async getNodeDirectory(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return this.personDir;case"place":return this.placeDir;case"thing":return this.thingDir;case"event":return this.eventDir;case"concept":return this.conceptDir;case"content":return this.contentDir;default:return this.defaultDir}return this.defaultDir}catch(e){return this.defaultDir}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await xe.promises.readdir(e);for(const a of r){const r=we.join(e,a),s=await xe.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){console.warn(`Error calculating size for ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.personDir),o=await t(this.placeDir),i=await t(this.thingDir),c=await t(this.eventDir),u=await t(this.conceptDir),l=await t(this.contentDir),d=await t(this.defaultDir);e=n+r+a;let h=null,p={nounTypes:{person:{size:s,count:await this.countFilesInDirectory(this.personDir)},place:{size:o,count:await this.countFilesInDirectory(this.placeDir)},thing:{size:i,count:await this.countFilesInDirectory(this.thingDir)},event:{size:c,count:await this.countFilesInDirectory(this.eventDir)},concept:{size:u,count:await this.countFilesInDirectory(this.conceptDir)},content:{size:l,count:await this.countFilesInDirectory(this.contentDir)},default:{size:d,count:await this.countFilesInDirectory(this.defaultDir)}}};try{const e=await xe.promises.statfs(this.rootDir);if(e){const t=e.bavail*e.bsize,n=e.blocks*e.bsize;h=n,p={availableSpace:t,totalSpace:n,freePercentage:t/n*100}}}catch(e){console.warn("Unable to get filesystem stats:",e);try{const{exec:e}=await Promise.resolve().then(function(){return bF}),t=(await Promise.resolve().then(function(){return Vc})).promisify(e),{stdout:n}=await t(`df -k "${this.rootDir}"`),r=n.trim().split("\n");if(r.length>1){const e=r[1].split(/\s+/);if(e.length>=4){const t=parseInt(e[1],10),n=(parseInt(e[2],10),parseInt(e[3],10));h=1024*t,p={availableSpace:1024*n,totalSpace:1024*t,freePercentage:n/t*100}}}}catch(e){console.warn("Unable to get disk space using df command:",e)}}return{type:"filesystem",used:e,quota:h,details:p}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}}var ke=Object.freeze({__proto__:null,FileSystemStorage:ve});const Ie="nouns/",Se="verbs/",Ne="verbs/",Te="metadata/",Ee="nouns/person/",$e="place/",Ce="thing/",Re="event/",Ae="concept/",_e="content/",De="default/";class Oe{async saveNoun(e){return this.saveNode(e)}async getNoun(e){return this.getNode(e)}async getAllNouns(){return this.getAllNodes()}async getNounsByNounType(e){return this.getNodesByNounType(e)}async deleteNoun(e){return this.deleteNode(e)}async saveVerb(e){return this.saveEdge(e)}async getVerb(e){return this.getEdge(e)}async getAllVerbs(){return this.getAllEdges()}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getVerbsByType(e){return this.getEdgesByType(e)}async deleteVerb(e){return this.deleteEdge(e)}constructor(e){this.isInitialized=!1,this.bucketName=e.bucketName,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.serviceType=e.serviceType,this.accountId=e.accountId,this.region=e.region,this.endpoint=e.endpoint}async init(){if(!this.isInitialized)try{try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};switch(this.serviceType){case"r2":if(!this.accountId)throw new Error("accountId is required for Cloudflare R2");t.region="auto",t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`;break;case"s3":if(!this.region)throw new Error("region is required for Amazon S3");t.region=this.region;break;case"gcs":this.endpoint||(this.endpoint="https://storage.googleapis.com"),t.endpoint=this.endpoint,t.region=this.region||"auto";break;case"custom":if(!this.endpoint)throw new Error("endpoint is required for custom S3-compatible services");t.endpoint=this.endpoint,this.region&&(t.region=this.region);break;default:throw new Error(`Unsupported service type: ${this.serviceType}`)}this.s3Client=new e(t),this.isInitialized=!0}catch(e){throw new Error(`Failed to import AWS SDK: ${e}. Make sure @aws-sdk/client-s3 is installed.`)}}catch(e){throw console.error(`Failed to initialize ${this.serviceType} storage:`,e),new Error(`Failed to initialize ${this.serviceType} storage: ${e}`)}}async saveNode(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodePrefix(e.id),{PutObjectCommand:r}=await import("@aws-sdk/client-s3");await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${n}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNode(e){await this.ensureInitialized();try{const t=await this.getNodePrefix(e),{GetObjectCommand:n}=await import("@aws-sdk/client-s3");try{const r=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${t}${e}.json`})),a=await r.Body.transformToString(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch(r){if(t!==De)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`})),r=await t.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch{const r=[Ee,$e,Ce,Re,Ae,_e];for(const a of r)if(a!==t)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${a}${e}.json`})),r=await t.Body.transformToString(),s=JSON.parse(r),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch{}}return null}}catch(t){return console.error(`Failed to get node ${e}:`,t),null}}async getNodesByNounType(e){await this.ensureInitialized();try{let t;switch(e){case"person":t=Ee;break;case"place":t=$e;break;case"thing":t=Ce;break;case"event":t=Re;break;case"concept":t=Ae;break;case"content":t=_e;break;default:t=De}const{ListObjectsV2Command:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3"),a=await this.s3Client.send(new n({Bucket:this.bucketName,Prefix:`${Ie}${t}`})),s=[];if(!a.Contents||0===a.Contents.length)return s;const o=a.Contents.map(async e=>{try{const t=await this.s3Client.send(new r({Bucket:this.bucketName,Key:e.Key})),n=await t.Body.transformToString(),a=JSON.parse(n),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(t){return console.error(`Failed to get node from ${e.Key}:`,t),null}});return(await Promise.all(o)).filter(e=>null!==e)}catch(t){throw console.error(`Failed to get nodes for noun type ${e}:`,t),new Error(`Failed to get nodes for noun type ${e}: ${t}`)}}async getAllNodes(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNodesByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nodes:",e),new Error(`Failed to get all nodes: ${e}`)}}async deleteNode(e){await this.ensureInitialized();try{const t=await this.getNodePrefix(e),{DeleteObjectCommand:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3");try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${t}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${t}${e}.json`}))}catch{if(t!==De)try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`}))}catch{const a=[Ee,$e,Ce,Re,Ae,_e];for(const s of a)if(s!==t)try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${Ie}${s}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${s}${e}.json`}))}catch{}}return}}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Se}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getEdge(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Se}${e}.json`})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch{return null}}catch(t){return console.error(`Failed to get edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:Se})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch(t){return console.error(`Failed to get edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getEdgesBySource(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getEdgesByTarget(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getEdgesByType(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t,GetObjectCommand:n}=await import("@aws-sdk/client-s3");try{await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ne}${e}.json`})),await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Ne}${e}.json`}))}catch{return}}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{const{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Te}${e}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Te}${e}.json`})),r=await n.Body.transformToString();return JSON.parse(r)}catch{return null}}catch(t){return console.error(`Failed to get metadata for ${e}:`,t),null}}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName}));if(!n.Contents||0===n.Contents.length)return;const r=n.Contents.map(async e=>{try{await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))}catch(t){console.error(`Failed to delete object ${e.Key}:`,t)}});await Promise.all(r)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async getStorageStatus(){await this.ensureInitialized();try{const{ListObjectsV2Command:e}=await import("@aws-sdk/client-s3"),t=await this.s3Client.send(new e({Bucket:this.bucketName}));let n=0,r=0,a=0,s=0;if(t.Contents)for(const e of t.Contents){n+=e.Size||0;const t=e.Key||"";t.startsWith(Ie)?r++:t.startsWith(Se)?a++:t.startsWith(Te)&&s++}const o={person:0,place:0,thing:0,event:0,concept:0,content:0,default:0},i=[{type:"person",prefix:Ee},{type:"place",prefix:$e},{type:"thing",prefix:Ce},{type:"event",prefix:Re},{type:"concept",prefix:Ae},{type:"content",prefix:_e},{type:"default",prefix:De}];for(const{type:t,prefix:n}of i){const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:`${Ie}${n}`}));o[t]=r.Contents?.length||0}return{type:this.serviceType,used:n,quota:null,details:{nodeCount:r,edgeCount:a,metadataCount:s,nounTypes:{person:{count:o.person},place:{count:o.place},thing:{count:o.thing},event:{count:o.event},concept:{count:o.concept},content:{count:o.content},default:{count:o.default}}}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}async ensureInitialized(){this.isInitialized||await this.init()}async getNodePrefix(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return Ee;case"place":return $e;case"thing":return Ce;case"event":return Re;case"concept":return Ae;case"content":return _e;default:return De}return De}catch(e){return De}}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}var Fe=Object.freeze({__proto__:null,R2Storage:Oe,S3CompatibleStorage:Oe});let Me=null;const Pe=[];function Be(e){return void 0===e.enabled&&(e.enabled=!0),Pe.push(e),e}function Le(e){const t=e||Me;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Pe)e.enabled&&t.register(e);return t}function ze(e,t){const n=Pe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function We(e){return Pe.filter(t=>{switch(e){case le.SENSE:return"processRawData"in t&&"listenToFeed"in t;case le.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case le.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case le.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case le.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case le.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case le.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case le.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class Ve{constructor(e){this.enabled=!0,this.isInitialized=!1,this.name=e.name,this.description=e.description||`${e.name} augmentation`,this.enabled=!1!==e.enabled}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}function Ue(e){const t=new Ve(e);return t.processRawData=async(n,r)=>{if(await t.ensureInitialized(),e.processRawData){const t=e.processRawData(n,r);return t instanceof Promise?await t:t}return{success:!1,data:{nouns:[],verbs:[]},error:"processRawData not implemented"}},t.listenToFeed=async(n,r)=>{if(await t.ensureInitialized(),e.listenToFeed)return e.listenToFeed(n,r);throw new Error("listenToFeed not implemented")},e.autoRegister&&(Be(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function Ge(e,t){const n=e;return n.connectWebSocket=async(n,r)=>{if(await(e.ensureInitialized?.()),t.connectWebSocket)return t.connectWebSocket(n,r);throw new Error("connectWebSocket not implemented")},n.sendWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.sendWebSocketMessage)return t.sendWebSocketMessage(n,r);throw new Error("sendWebSocketMessage not implemented")},n.onWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.onWebSocketMessage)return t.onWebSocketMessage(n,r);throw new Error("onWebSocketMessage not implemented")},n.offWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.offWebSocketMessage)return t.offWebSocketMessage(n,r);throw new Error("offWebSocketMessage not implemented")},n.closeWebSocket=async(n,r,a)=>{if(await(e.ensureInitialized?.()),t.closeWebSocket)return t.closeWebSocket(n,r,a);throw new Error("closeWebSocket not implemented")},n}async function He(e,t,...n){try{if(!e.enabled)return{success:!1,data:null,error:`Augmentation ${e.name} is disabled`};if("function"!=typeof e[t])return{success:!1,data:null,error:`Method ${t} not found on augmentation ${e.name}`};return await e[t](...n)}catch(n){return console.error(`Error executing ${t} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}}async function je(e,t={}){try{const n=await e,r=[];for(const e in n){const a=n[e];a&&"object"==typeof a&&("string"==typeof a.name&&"function"==typeof a.initialize&&"function"==typeof a.shutDown&&"function"==typeof a.getStatus&&(r.push(a),t.autoRegister&&(Be(a),t.autoInitialize&&a.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${a.name}:`,e)}))))}return r}catch(e){return console.error("Error loading augmentation module:",e),[]}}var qe;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(qe||(qe={}));const Ke={mode:qe.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class Xe{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case le.SENSE:return[...this.registry.sense];case le.CONDUIT:return[...this.registry.conduit];case le.COGNITION:return[...this.registry.cognition];case le.MEMORY:return[...this.registry.memory];case le.PERCEPTION:return[...this.registry.perception];case le.DIALOG:return[...this.registry.dialog];case le.ACTIVATION:return[...this.registry.activation];case le.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(le.SENSE),this.registry.conduit.length>0&&e.push(le.CONDUIT),this.registry.cognition.length>0&&e.push(le.COGNITION),this.registry.memory.length>0&&e.push(le.MEMORY),this.registry.perception.length>0&&e.push(le.PERCEPTION),this.registry.dialog.length>0&&e.push(le.DIALOG),this.registry.activation.length>0&&e.push(le.ACTIVATION),this.registry.webSocket.length>0&&e.push(le.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===qe.THREADED)&&C())}async execute(e,t,n=[],r={}){const a={...Ke,...r},s=e.filter(e=>!1!==e.enabled);if(0===s.length)return{results:[],errors:[],successful:[]};const o={results:[],errors:[],successful:[]},i=async e=>{try{if(a.timeout){const r=new Promise((n,r)=>{setTimeout(()=>{r(new Error(`Timeout executing ${t} on ${e.name}`))},a.timeout)});let s;if(this.shouldUseThreading(a))try{s=A(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return await Promise.race([s,r])}return await He(e,t,...n)}catch(e){return o.errors.push(e instanceof Error?e:new Error(String(e))),{success:!1,data:null,error:e instanceof Error?e.message:String(e)}}};switch(a.mode){case qe.PARALLEL:case qe.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case qe.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case qe.FIRST_RESULT:for(const e of s){const t=await i(e);if(o.results.push(t),t.success&&null!==t.data&&void 0!==t.data)break}break;case qe.SEQUENTIAL:default:for(const e of s){const t=await i(e);if(o.results.push(t),a.stopOnError&&!t.success)break}}return o.successful=o.results.filter(e=>e.success),o}async executeByType(e,t,n=[],r={}){const a=this.getAugmentationsByType(e);return this.execute(a,t,n,r)}async executeSingle(e,t,...n){return He(e,t,...n)}async processStaticData(e,t,n={}){let r,a=e;for(const e of t){const t=e.transformArgs?e.transformArgs(a,r):[a],n=await this.executeSingle(e.augmentation,e.method,...t);if(!n.success)return n;a=n.data,r=n}return r}async processStreamingData(e,t,n,r,a,s={}){const o=async e=>{let t,n=e;for(const e of r){const r=e.transformArgs?e.transformArgs(n,t):[n],s=await this.executeSingle(e.augmentation,e.method,...r);if(!s.success)return void a(s);n=s.data,t=s}a(t)};await this.executeSingle(e,t,...n,e=>{o(e).catch(e=>{console.error("Error processing streaming data:",e),a({success:!1,data:null,error:e instanceof Error?e.message:String(e)})})})}createPipeline(e,t={}){return n=>this.processStaticData(n,e,t)}createStreamingPipeline(e,t,n,r={}){return(a,s)=>this.processStreamingData(e,t,a,n,s,r)}async executeSensePipeline(e,t,n={}){return(await this.executeByType(le.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(le.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(le.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(le.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(le.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(le.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(le.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const Ye=new Xe;!function(e){Me=e}(Ye);const Qe=Ye,Je=(e,t,n=[],r={})=>Ye.execute(e,t,n,r),Ze=(e,t,n=[],r={})=>Ye.executeByType(e,t,n,r),et=(e,t,...n)=>Ye.executeSingle(e,t,...n),tt=(e,t,n={})=>Ye.processStaticData(e,t,n),nt=(e,t,n,r,a,s={})=>Ye.processStreamingData(e,t,n,r,a,s),rt=(e,t={})=>Ye.createPipeline(e,t),at=(e,t,n,r={})=>Ye.createStreamingPipeline(e,t,n,r),st=qe;var ot;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(ot||(ot={}));const it={mode:ot.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const ct=new class{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}async executeSensePipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.activation,e,t,r)}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case le.SENSE:return[...this.registry.sense];case le.CONDUIT:return[...this.registry.conduit];case le.COGNITION:return[...this.registry.cognition];case le.MEMORY:return[...this.registry.memory];case le.PERCEPTION:return[...this.registry.perception];case le.DIALOG:return[...this.registry.dialog];case le.ACTIVATION:return[...this.registry.activation];case le.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(le.SENSE),this.registry.conduit.length>0&&e.push(le.CONDUIT),this.registry.cognition.length>0&&e.push(le.COGNITION),this.registry.memory.length>0&&e.push(le.MEMORY),this.registry.perception.length>0&&e.push(le.PERCEPTION),this.registry.dialog.length>0&&e.push(le.DIALOG),this.registry.activation.length>0&&e.push(le.ACTIVATION),this.registry.webSocket.length>0&&e.push(le.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===ot.THREADED)&&C())}async executeTypedPipeline(e,t,n,r){const a=e.filter(e=>!1!==e.enabled);if(0===a.length)return[];const s=async e=>{try{const a=r.timeout?new Promise((n,a)=>{setTimeout(()=>{a(new Error(`Timeout executing ${String(t)} on ${e.name}`))},r.timeout)}):null;let s;if(this.shouldUseThreading(r))try{s=A(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return a?await Promise.race([s,a]):await s}catch(n){return console.error(`Error executing ${String(t)} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}};switch(r.mode){case ot.PARALLEL:return a.map(s);case ot.THREADED:const e={...r,forceThreading:!0},t=async t=>{const n=r;r=e;const a=await s(t);return r=n,a};return a.map(t);case ot.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case ot.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case ot.SEQUENTIAL:default:const n=[];for(const e of a){const t=s(e);if(n.push(t),r.stopOnError){if(!(await t).success)break}}return n}}};let ut,lt,dt;const ht=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(ut=globalThis.TransformStream,lt=globalThis.ReadableStream,dt=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{ut=e.TransformStream,lt=e.ReadableStream,dt=e.WritableStream}).catch(e=>{throw console.error("Failed to import WebStreams API:",e),new Error("WebStreams API is not available in this environment. Please use a modern browser or Node.js 18+.")}),pt={timeout:3e4,stopOnError:!1};class ft{constructor(e={}){this.brainyData=e.brainyData||new be}async ensureStreamClassesInitialized(){await ht}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...pt,...n},a={success:!0,data:null,stageResults:{}};try{const n=await ct.executeSensePipeline("processRawData",[e,t],{timeout:r.timeout,stopOnError:r.stopOnError});let s=null;for(const e of n){const t=await e;if(t.success){s=t;break}}if(!s||!s.success)return{success:!1,data:null,error:"Failed to process raw data with ISense augmentations",stageResults:{sense:s||{success:!1,data:null,error:"No sense augmentations available"}}};a.stageResults.sense=s;const o=ct.getAugmentationsByType(le.MEMORY);if(0===o.length)return{success:!1,data:null,error:"No memory augmentations available",stageResults:a.stageResults};const i=o[0],c=`data_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,u=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!u.success)return{success:!1,data:null,error:`Failed to store data: ${u.error}`,stageResults:{...a.stageResults,memory:u}};a.stageResults.memory=u;const l=await ct.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of l){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await ct.executeConduitPipeline("writeData",[{dataKey:c,nouns:s.data.nouns,verbs:s.data.verbs}],{timeout:r.timeout,stopOnError:r.stopOnError});let p=null;for(const e of h){const t=await e;if(t.success){p=t;break}}p&&(a.stageResults.conduit=p);const f=await ct.executeActivationPipeline("triggerAction",["dataProcessed",{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let m=null;for(const e of f){const t=await e;if(t.success){m=t;break}}m&&(a.stageResults.activation=m);const g=await ct.executePerceptionPipeline("interpret",[s.data.nouns,s.data.verbs,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let y=null;for(const e of g){const t=await e;if(t.success){y=t;break}}return y?(a.stageResults.perception=y,a.data=y.data):a.data=d?d.data:{dataKey:c},a}catch(e){return{success:!1,data:null,error:`Pipeline execution failed: ${e}`,stageResults:a.stageResults}}}async createWebSocketHandler(e,t,n={}){await this.ensureStreamClassesInitialized();const r=new ut({transform:async(e,r)=>{try{const a="string"==typeof e?e:JSON.stringify(e),s=await this.processData(a,t,n);s.success?r.enqueue(s):console.warn("Pipeline processing failed:",s.error)}catch(e){console.error("Error in transform stream:",e)}}}),a=new dt({write:async t=>{if(e.send&&"function"==typeof e.send)try{await e.send(JSON.stringify(t))}catch(e){console.error("Error sending result back to WebSocket:",e)}}});return r.readable.pipeTo(a).catch(e=>{console.error("Error in pipeline stream:",e)}),e=>{try{const t=r.writable.getWriter();t.write(e).catch(e=>{console.error("Error writing to stream:",e)}).finally(()=>{t.releaseLock()})}catch(e){console.error("Error getting writer for transform stream:",e)}}}async setupWebSocketPipeline(e,t,n={}){await this.ensureStreamClassesInitialized();const r=ct.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new lt({start:e=>{const t=t=>{try{const n="string"==typeof t.data?t.data:t.data instanceof Blob?new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.readAsText(t.data)}):JSON.stringify(t.data);n instanceof Promise?n.then(t=>{e.enqueue(t)}).catch(e=>{console.error("Error processing blob data:",e)}):e.enqueue(n)}catch(e){console.error("Error processing WebSocket message:",e)}},n=e=>{t({data:e})};s._streamMessageHandler=t,s._messageHandlerWrapper=n,a.onWebSocketMessage(s.connectionId,n).catch(t=>{console.error("Error registering WebSocket message handler:",t),e.error(t)})},cancel:()=>{s._messageHandlerWrapper&&(a.offWebSocketMessage(s.connectionId,s._messageHandlerWrapper).catch(e=>{console.error("Error removing WebSocket message handler:",e)}),delete s._streamMessageHandler,delete s._messageHandlerWrapper)}}),i=this.createWebSocketHandler(s,t,n),c=new dt({write:async e=>{if(!s.send||"function"!=typeof s.send)throw new Error("WebSocket connection does not support sending data");try{const t="string"==typeof e?e:JSON.stringify(e);await s.send(t)}catch(e){throw console.error("Error sending data to WebSocket:",e),e}},close:()=>{s.close&&"function"==typeof s.close&&s.close().catch(e=>{console.error("Error closing WebSocket connection:",e)})}});o.pipeThrough(new ut({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new dt({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const u=s;return u.readableStream=o,u.writableStream=c,u}}const mt=new ft,gt={autoInitialize:!1,debug:!1};async function yt(e,t={}){const n={...gt,...t},r={augmentations:[],errors:[]};n.debug&&console.log(`[AugmentationRegistryLoader] Loading augmentations from ${Object.keys(e).length} modules`);for(const[t,a]of Object.entries(e))try{n.debug&&console.log(`[AugmentationRegistryLoader] Processing module: ${t}`);const e=bt(a);if(0===e.length){n.debug&&console.log(`[AugmentationRegistryLoader] No augmentations found in module: ${t}`);continue}for(const t of e)try{const e=Be(t);r.augmentations.push(e),n.debug&&console.log(`[AugmentationRegistryLoader] Registered augmentation: ${e.name}`)}catch(e){const t=e instanceof Error?e:new Error(String(e));r.errors.push(t),n.debug&&console.error(`[AugmentationRegistryLoader] Failed to register augmentation: ${t.message}`)}}catch(e){const a=e instanceof Error?e:new Error(String(e));r.errors.push(a),n.debug&&console.error(`[AugmentationRegistryLoader] Error processing module ${t}: ${a.message}`)}return n.debug&&console.log(`[AugmentationRegistryLoader] Loaded ${r.augmentations.length} augmentations with ${r.errors.length} errors`),r}function bt(e){const t=[];if(xt(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(xt(r)&&t.push(r),Array.isArray(r)&&r.every(xt)&&t.push(...r))}return t}function xt(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function wt(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function vt(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class kt{constructor(e,t){this.description="Base memory augmentation",this.enabled=!0,this.isInitialized=!1,this.name=e,this.storage=t}async initialize(){if(!this.isInitialized)try{await this.storage.init(),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async storeData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to store data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to store data: ${t}`}}}async retrieveData(e,t){await this.ensureInitialized();try{return{success:!0,data:await this.storage.getMetadata(e)}}catch(t){return console.error(`Failed to retrieve data for key ${e}:`,t),{success:!1,data:null,error:`Failed to retrieve data: ${t}`}}}async updateData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to update data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to update data: ${t}`}}}async deleteData(e,t){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,null),{success:!0,data:!0}}catch(t){return console.error(`Failed to delete data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to delete data: ${t}`}}}async listDataKeys(e,t){return{success:!1,data:[],error:"listDataKeys is not supported by this storage adapter"}}async search(e,t=10,n){await this.ensureInitialized();try{let n;if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))return{success:!1,data:[],error:"Query must be a vector (array of numbers) for vector search"};n=e;const r=await this.storage.getAllNouns(),a=[];for(const e of r){if(!e.vector||!Array.isArray(e.vector))continue;const t=await this.storage.getMetadata(e.id),r=1-I(n,e.vector);a.push({id:e.id,score:r,data:t})}a.sort((e,t)=>t.score-e.score);return{success:!0,data:a.slice(0,t)}}catch(e){return console.error("Failed to search in storage:",e),{success:!1,data:[],error:`Failed to search in storage: ${e}`}}}async ensureInitialized(){this.isInitialized||await this.initialize()}}class It extends kt{constructor(e){super(e,new oe),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return le.MEMORY}}class St extends kt{constructor(e,t){super(e,new ve(t)),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return le.MEMORY}}class Nt extends kt{constructor(e){super(e,new se),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return le.MEMORY}}async function Tt(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new It(e);case"filesystem":return new St(e,t.rootDirectory);case"opfs":return new Nt(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new St(e,t.rootDirectory);{const n=new se;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new Nt(e)):new It(e)}}const Et="1.0.0";var $t;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}($t||($t={}));class Ct{constructor(e){this.brainyData=e}async handleRequest(e){try{switch(e.operation){case"get":return await this.handleGetRequest(e);case"search":return await this.handleSearchRequest(e);case"add":return await this.handleAddRequest(e);case"getRelationships":return await this.handleGetRelationshipsRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_OPERATION",`Operation ${e.operation} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleGetRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await this.brainyData.get(t);return n?this.createSuccessResponse(e.requestId,n):this.createErrorResponse(e.requestId,"NOT_FOUND",`No noun found with id ${t}`)}async handleSearchRequest(e){const{query:t,k:n=10}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "query" is required');const r=await this.brainyData.searchText(t,n);return this.createSuccessResponse(e.requestId,r)}async handleAddRequest(e){const{text:t,metadata:n}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "text" is required');const r=await this.brainyData.add(t,n);return this.createSuccessResponse(e.requestId,{id:r})}async handleGetRelationshipsRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await(this.brainyData.getVerbsBySource?.(t))||[],r=await(this.brainyData.getVerbsByTarget?.(t))||[];return this.createSuccessResponse(e.requestId,{outgoing:n,incoming:r})}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}}class Rt{constructor(){}async handleRequest(e){try{const{toolName:t,parameters:n}=e,r=t.split("_");if(r.length<3||"brainy"!==r[0])return this.createErrorResponse(e.requestId,"INVALID_TOOL",`Invalid tool name: ${t}. Tool names should be in the format: brainy_{augmentationType}_{method}`);const a=r[1],s=r.slice(2).join("_");if(!this.isValidAugmentationType(a))return this.createErrorResponse(e.requestId,"INVALID_AUGMENTATION_TYPE",`Invalid augmentation type: ${a}`);const o=await this.executePipeline(a,s,n);return this.createSuccessResponse(e.requestId,o)}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async getAvailableTools(){const e=[],t=ct.getAvailableAugmentationTypes();for(const n of t){const t=ct.getAugmentationsByType(n);for(const r of t){const t=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(e=>!e.startsWith("_")&&"constructor"!==e&&"initialize"!==e&&"shutDown"!==e&&"getStatus"!==e&&"function"==typeof r[e]);for(const a of t)e.push(this.createToolDefinition(n,r.name,a))}}return e}createToolDefinition(e,t,n){return{name:`brainy_${e}_${n}`,description:`Access to Brainy's ${e} augmentation '${t}' method '${n}'`,parameters:{type:"object",properties:{args:{type:"array",description:`Arguments for the ${n} method`},options:{type:"object",description:"Optional execution options"}},required:["args"]}}}async executePipeline(e,t,n){const{args:r=[],options:a={}}=n;switch(e){case le.SENSE:return await ct.executeSensePipeline(t,r,a);case le.CONDUIT:return await ct.executeConduitPipeline(t,r,a);case le.COGNITION:return await ct.executeCognitionPipeline(t,r,a);case le.MEMORY:return await ct.executeMemoryPipeline(t,r,a);case le.PERCEPTION:return await ct.executePerceptionPipeline(t,r,a);case le.DIALOG:return await ct.executeDialogPipeline(t,r,a);case le.ACTIVATION:return await ct.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(le).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}}class At{constructor(e,t={}){this.dataAdapter=new Ct(e),this.toolset=new Rt,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case $t.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case $t.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case $t.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case $t.AUTHENTICATION:return await this.handleAuthenticationRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_REQUEST_TYPE",`Request type ${e.type} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleSystemInfoRequest(e){try{switch(e.infoType){case"status":return this.createSuccessResponse(e.requestId,{status:"active",version:Et,environment:E()?"browser":$()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:Et});default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_INFO_TYPE",`Info type ${e.infoType} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleAuthenticationRequest(e){try{if(!this.options.enableAuth)return this.createSuccessResponse(e.requestId,{authenticated:!0,message:"Authentication is not enabled"});const{credentials:t}=e;if(t.apiKey&&this.options.apiKeys?.includes(t.apiKey)){const t=this.generateAuthToken("api-user");return this.createSuccessResponse(e.requestId,{authenticated:!0,token:t})}if("admin"===t.username&&"password"===t.password){const n=this.generateAuthToken(t.username);return this.createSuccessResponse(e.requestId,{authenticated:!0,token:n})}return this.createErrorResponse(e.requestId,"INVALID_CREDENTIALS","Invalid credentials")}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}isValidRequest(e){return e&&"object"==typeof e&&e.type&&e.requestId&&e.version}isAuthenticated(e){return!this.options.enableAuth||!!e.authToken&&this.isValidToken(e.authToken)}isValidToken(e){const t=this.authTokens.get(e);return!!t&&(!(t.expires<Date.now())||(this.authTokens.delete(e),!1))}generateAuthToken(e){const t=v(),n=Date.now()+864e5;return this.authTokens.set(t,{userId:e,expires:n}),t}checkRateLimit(e){if(!this.options.rateLimit)return!0;const t=Date.now(),n=this.rateLimits.get(e);return n?n.resetTime<t?(n.count=1,n.resetTime=t+this.options.rateLimit.windowMs,!0):!(n.count>=this.options.rateLimit.maxRequests)&&(n.count++,!0):(this.rateLimits.set(e,{count:1,resetTime:t+this.options.rateLimit.windowMs}),!0)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=s.Buffer);const _t={isBrowser:"undefined"!=typeof window,isNode:"undefined"!=typeof process&&process.versions&&process.versions.node,isServerless:!("undefined"!=typeof window||"undefined"!=typeof process&&process.versions&&process.versions.node)};"undefined"!=typeof globalThis&&(globalThis.__ENV__=_t),console.log(`Brainy running in ${_t.isBrowser?"browser":_t.isNode?"Node.js":"serverless/unknown"} environment`);class Dt{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class Ot{refCount(e){return Ft("refCount")}incRef(e){return Ft("incRef")}timerAvailable(){return!0}time(e){return Ft("time")}read(e){return Ft("read")}readSync(e){return Ft("readSync")}readToGPU(e,t){return Ft("readToGPU")}numDataIds(){return Ft("numDataIds")}disposeData(e,t){return Ft("disposeData")}write(e,t,n){return Ft("write")}move(e,t,n,r,a){return Ft("move")}createTensorFromGPUData(e,t,n){return Ft("createTensorFromGPUData")}memory(){return Ft("memory")}floatPrecision(){return Ft("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Ft("dispose")}}function Ft(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
9
+ function(e){const t=o,n=m,r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=i,e.SlowBuffer=function(e){+e!=e&&(e=0);return i.alloc(+e)},e.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,i.prototype),t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=s(n);const a=r.write(e,t);a!==n&&(r=r.slice(0,a));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);const a=function(e){if(i.isBuffer(e)){const t=0|p(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||Y(e.length)?s(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return u(e),s(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=s(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,i.prototype),r}function p(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function f(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let a=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(a)return r?-1:j(e).length;t=(""+t).toLowerCase(),a=!0}}function g(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return $(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return N(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,a){let s,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(u(e,s)===u(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(u(e,s+r)!==u(t,r)){n=!1;break}if(n)return s}return-1}function w(e,t,n,r){n=Number(n)||0;const a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(Y(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return K(j(t,e.length-n),e,n,r)}function k(e,t,n,r){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function I(e,t,n,r){return K(q(t),e,n,r)}function S(e,t,n,r){return K(function(e,t){let n,r,a;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function N(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function T(e,t,n){n=Math.min(e.length,n);const r=[];let a=t;for(;a<n;){const t=e[a];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(a+o<=n){let n,r,i,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[a+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[a+1],r=e[a+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[a+1],r=e[a+2],i=e[a+3],128==(192&n)&&128==(192&r)&&128==(192&i)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&i,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),a+=o}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=E));return n}(r)}e.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(e,t,n){return function(e,t,n){return u(e),e<=0?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}(e,t,n)},i.allocUnsafe=function(e){return l(e)},i.allocUnsafeSlow=function(e){return l(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=i.allocUnsafe(t);let a=0;for(n=0;n<e.length;++n){let t=e[n];if(X(t,Uint8Array))a+t.length>r.length?(i.isBuffer(t)||(t=i.from(t)),t.copy(r,a)):Uint8Array.prototype.set.call(r,t,a);else{if(!i.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,a)}a+=t.length}return r},i.byteLength=f,i.prototype._isBuffer=!0,i.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},i.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},i.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},i.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(i.prototype[r]=i.prototype.inspect),i.prototype.compare=function(e,t,n,r,a){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0);const c=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){s=u[e],o=l[e];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return b(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return b(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function $(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function C(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function R(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let a="";for(let r=t;r<n;++r)a+=Q[e[r]];return a}function A(e,t,n){const r=e.slice(t,n);let a="";for(let e=0;e<r.length-1;e+=2)a+=String.fromCharCode(r[e]+256*r[e+1]);return a}function _(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function O(e,t,n,r,a){V(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function F(e,t,n,r,a){V(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function M(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,a,23,4),r+4}function B(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,a,52,8),r+8}i.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,i.prototype),r},i.prototype.readUintLE=i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUintBE=i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e+--t],a=1;for(;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUint8=i.prototype.readUInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),this[e]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readBigUInt64LE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,a=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(a)<<BigInt(32))}),i.prototype.readBigUInt64BE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],a=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(a)}),i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=t,a=1,s=this[e+--r];for(;r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readBigInt64LE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),i.prototype.readBigInt64BE=J(function(e){U(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),i.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUint8=i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigUInt64LE=J(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}let a=0,s=1,o=0;for(this[t]=255&e;++a<n&&(s*=256);)e<0&&0===o&&0!==this[t+a-1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}let a=n-1,s=1,o=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigInt64LE=J(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const a=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),a},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{const s=i.isBuffer(e)?e:i.from(e,r),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=s[a%o]}return this};const L={};function z(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function W(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function V(e,t,n,r,a,s){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){U(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,a,s)}function U(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw U(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}z("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),z("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,a=n;return Number.isInteger(n)&&Math.abs(n)>2**32?a=W(String(n)):"bigint"==typeof n&&(a=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(a=W(a)),a+="n"),r+=` It must be ${t}. Received ${a}`,r},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function j(e,t){let n;t=t||1/0;const r=e.length;let a=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,r){let a;for(a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let a=0;a<16;++a)t[r+a]=e[n]+e[a]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(s);const y=new Uint8Array(16);function b(){if(!g&&(g="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(y)}const x=[];for(let e=0;e<256;++e)x.push((e+256).toString(16).slice(1));var w={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v(e,t,n){if(w.randomUUID&&!e)return w.randomUUID();const r=(e=e||{}).random||(e.rng||b)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+"-"+x[e[t+4]]+x[e[t+5]]+"-"+x[e[t+6]]+x[e[t+7]]+"-"+x[e[t+8]]+x[e[t+9]]+"-"+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]}(r)}const k=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>{const a=n-t[r];return e+a*a},0);return Math.sqrt(n)},I=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const{dotProduct:n,normA:r,normB:a}=e.reduce((e,n,r)=>({dotProduct:e.dotProduct+n*t[r],normA:e.normA+n*n,normB:e.normB+t[r]*t[r]}),{dotProduct:0,normA:0,normB:0});if(0===r||0===a)return 2;return 1-n/(Math.sqrt(r)*Math.sqrt(a))},S=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");return e.reduce((e,n,r)=>e+Math.abs(n-t[r]),0)},N=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>e+n*t[r],0);return-n};async function T(e,t,n=k){if(t.length<10)return t.map(t=>n(e,t));try{return t.map(t=>n(e,t))}catch(r){return console.error("Batch distance calculation failed:",r),t.map(t=>n(e,t))}}function E(){return"undefined"!=typeof window&&"undefined"!=typeof document}function $(){return"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node}function C(){return E()&&"undefined"!=typeof Worker||function(){if(!$())return!1;try{return require("worker_threads"),!0}catch(e){return!1}}()}const R=new Map;function A(e,t){if($())return function(e,t){return new Promise((n,r)=>{try{import("node:worker_threads").then(({Worker:a,isMainThread:s,parentPort:o,workerData:i})=>{if(!s&&o){const e=new Function("return "+i.fnString)()(i.args);return void o.postMessage({result:e})}const c=`worker-${Math.random().toString(36).substring(2,9)}`;let u;if(R.size<4)u=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),R.set(c,u);else{const n=Array.from(R.keys()),r=n[Math.floor(Math.random()*n.length)];u=R.get(r),u._busy&&(u.terminate(),u=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),R.set(r,u)),u._busy=!0}u.on("message",e=>{u._busy=!1,n(e.result)}),u.on("error",e=>{u._busy=!1,r(e)}),u.on("exit",e=>{0!==e&&(u._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(E()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{const a=new Blob(["\n self.onmessage = function(e) {\n try {\n const fn = new Function('return ' + e.data.fnString)();\n const result = fn(e.data.args);\n self.postMessage({ result: result });\n } catch (error) {\n self.postMessage({ error: error.message });\n }\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(a),o=new Worker(s);o.onmessage=function(e){e.data.error?r(new Error(e.data.error)):n(e.data.result),o.terminate(),URL.revokeObjectURL(s)},o.onerror=function(e){r(new Error(`Worker error: ${e.message}`)),o.terminate(),URL.revokeObjectURL(s)},o.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{const n=new Function("return "+e)();return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function _(){$()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of R.values())e.terminate();R.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let D=class{constructor(){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu"}addNodeCompatibilityPolyfills(){"undefined"!=typeof process&&process.versions&&process.versions.node}async init(){try{const e=console.warn;console.warn=function(t,...n){t&&"string"==typeof t&&t.includes("Hi, looks like you are running TensorFlow.js in Node.js")||e(t,...n)},this.addNodeCompatibilityPolyfills(),this.tf=await Promise.resolve().then(function(){return vy}),await Promise.resolve().then(function(){return rS});try{if("undefined"!=typeof window){await Promise.resolve().then(function(){return FD});try{this.tf.setBackend?(await this.tf.setBackend("webgl"),this.backend="webgl",console.log("Using WebGL backend for TensorFlow.js")):console.warn("tf.setBackend is not available, falling back to CPU")}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}}}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}this.tf.setBackend&&await this.tf.setBackend(this.backend),this.use=await Promise.resolve().then(function(){return mF}),console.log("Universal Sentence Encoder module structure in main thread:",Object.keys(this.use),this.use.default?Object.keys(this.use.default):"No default export");const t=function(e){console.log("Universal Sentence Encoder module structure:",Object.keys(e),e.default?Object.keys(e.default):"No default export");let t=null;if(e.load&&"function"==typeof e.load)t=e.load,console.log("Using sentenceEncoderModule.load");else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load,console.log("Using sentenceEncoderModule.default.load");else if(e.default&&"function"==typeof e.default)t=e.default,console.log("Using sentenceEncoderModule.default as function");else if("function"==typeof e)t=e,console.log("Using sentenceEncoderModule as function");else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load,console.log("Using sentenceEncoderModule.UniversalSentenceEncoder.load");else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.default.UniversalSentenceEncoder.load,console.log("Using sentenceEncoderModule.default.UniversalSentenceEncoder.load");else for(const n in e)if("function"==typeof e[n]){if((e[n].name||n).toLowerCase().includes("load")){t=e[n],console.log(`Using sentenceEncoderModule.${n} as load function`);break}}else if("object"==typeof e[n]&&null!==e[n]){for(const r in e[n])if("function"==typeof e[n][r]){if((e[n][r].name||r).toLowerCase().includes("load")){t=e[n][r],console.log(`Using sentenceEncoderModule.${n}.${r} as load function`);break}}if(t)break}return t}(this.use);if(!t)throw new Error("Could not find Universal Sentence Encoder load function");this.model=await t(),this.initialized=!0,console.warn=e}catch(e){throw console.error("Failed to initialize Universal Sentence Encoder:",e),new Error(`Failed to initialize Universal Sentence Encoder: ${e}`)}}async embed(e){this.initialized||await this.init();try{let t;if("string"==typeof e){if(""===e.trim())return new Array(512).fill(0);t=[e]}else{if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new Error("UniversalSentenceEncoder only supports string or string[] data");if(0===e.length||e.every(e=>""===e.trim()))return new Array(512).fill(0);if(t=e.filter(e=>""!==e.trim()),0===t.length)return new Array(512).fill(0)}const n=await this.model.embed(t),r=await n.array();return n.dispose(),r[0]}catch(e){throw console.error("Failed to embed text with Universal Sentence Encoder:",e),new Error(`Failed to embed text with Universal Sentence Encoder: ${e}`)}}async embedBatch(e){this.initialized||await this.init();try{if(0===e.length)return[];const t=e.filter(e=>"string"==typeof e&&""!==e.trim());if(0===t.length)return e.map(()=>new Array(512).fill(0));const n=await this.model.embed(t),r=await n.array();n.dispose();const a=[];let s=0;for(let t=0;t<e.length;t++){const n=e[t];"string"==typeof n&&""!==n.trim()?(a.push(r[s]),s++):a.push(new Array(512).fill(0))}return a}catch(e){throw console.error("Failed to batch embed text with Universal Sentence Encoder:",e),new Error(`Failed to batch embed text with Universal Sentence Encoder: ${e}`)}}async dispose(){if(this.model&&this.tf)try{this.model.dispose(),this.tf.disposeVariables(),this.initialized=!1}catch(e){console.error("Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function O(e){return async t=>await e.embed(t)}const F=new D;let M=!1;function P(){return async e=>{try{return M||(await F.init(),M=!0),await F.embed(e)}catch(e){throw console.error("Failed to use TensorFlow embedding:",e),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}const B=P(),L=new D;let z=!1;const W=async e=>{try{return z||(await L.init(),z=!0),await L.embedBatch(e)}catch(e){throw console.error("Failed to use TensorFlow batch embedding:",e),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}};function V(e){const t=O(e);return async e=>{const n=t.toString();return await A(n,e)}}var U=Object.freeze({__proto__:null,UniversalSentenceEncoder:D,createEmbeddingFunction:O,createTensorFlowEmbeddingFunction:P,createThreadedEmbeddingFunction:V,defaultBatchEmbeddingFunction:W,defaultEmbeddingFunction:B});const G={M:16,efConstruction:200,efSearch:50,ml:16};class H{constructor(e={},t=k,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...G,...e},this.distanceFunction=t,this.useParallelization=void 0===n.useParallelization||n.useParallelization}setUseParallelization(e){this.useParallelization=e}getUseParallelization(){return this.useParallelization}async calculateDistancesInParallel(e,t){if(!this.useParallelization||t.length<10)return t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}));try{const n=t.map(e=>e.vector),r=await T(e,n,this.distanceFunction);return t.map((e,t)=>({id:e.id,distance:r[t]}))}catch(n){return console.error("Error in GPU-accelerated distance calculation, falling back to sequential processing:",n),t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}))}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");if(null===this.dimension)this.dimension=n.length;else if(n.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${n.length}`);const r=this.getRandomLevel(),a={id:t,vector:n,connections:new Map};for(let e=0;e<=r;e++)a.connections.set(e,new Set);if(0===this.nouns.size)return this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;if(!this.entryPointId)return console.error("Entry point ID is null"),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;const s=this.nouns.get(this.entryPointId);if(!s)return console.error(`Entry point with ID ${this.entryPointId} not found`),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;let o=s,i=this.distanceFunction(n,s.vector);for(let e=this.maxLevel;e>r;e--){let t=!0;for(;t;){t=!1;const r=o.connections.get(e)||new Set;for(const e of r){const r=this.nouns.get(e);if(!r)continue;const a=this.distanceFunction(n,r.vector);a<i&&(i=a,o=r,t=!0)}}}for(let e=Math.min(r,this.maxLevel);e>=0;e--){const r=await this.searchLayer(n,o,this.config.efConstruction,e),s=this.selectNeighbors(n,r,this.config.M);for(const[n,r]of s){const r=this.nouns.get(n);r&&(a.connections.get(e).add(n),r.connections.has(e)||r.connections.set(e,new Set),r.connections.get(e).add(t),r.connections.get(e).size>this.config.M&&this.pruneConnections(r,e))}if(r.size>0){const[e,t]=[...r][0];if(t<i){i=t;const n=this.nouns.get(e);n?o=n:console.error(`Nearest noun with ID ${e} not found in addItem`)}}}return r>this.maxLevel&&(this.maxLevel=r,this.entryPointId=t),this.nouns.set(t,a),t}async search(e,t=10){if(0===this.nouns.size)return[];if(!e)throw new Error("Query vector is undefined or null");if(null!==this.dimension&&e.length!==this.dimension)throw new Error(`Query vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(!this.entryPointId)return console.error("Entry point ID is null"),[];const n=this.nouns.get(this.entryPointId);if(!n)return console.error(`Entry point with ID ${this.entryPointId} not found`),[];let r=n,a=this.distanceFunction(e,r.vector);for(let t=this.maxLevel;t>0;t--){let n=!0;for(;n;){n=!1;const s=r.connections.get(t)||new Set;if(this.useParallelization&&s.size>=10){const t=[];for(const e of s){const n=this.nouns.get(e);n&&t.push({id:e,vector:n.vector})}const o=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of o)if(t<a){a=t;const s=this.nouns.get(e);s&&(r=s,n=!0)}}else for(const t of s){const s=this.nouns.get(t);if(!s)continue;const o=this.distanceFunction(e,s.vector);o<a&&(a=o,r=s,n=!0)}}}return[...await this.searchLayer(e,r,Math.max(this.config.efSearch,t),0)].slice(0,t)}removeItem(e){if(!this.nouns.has(e))return!1;const t=this.nouns.get(e);for(const[n,r]of t.connections.entries())for(const t of r){const r=this.nouns.get(t);r&&(r.connections.has(n)&&(r.connections.get(n).delete(e),this.pruneConnections(r,n)))}for(const[t,n]of this.nouns.entries())if(t!==e)for(const[t,r]of n.connections.entries())r.has(e)&&(r.delete(e),this.pruneConnections(n,t));if(this.nouns.delete(e),this.entryPointId===e)if(0===this.nouns.size)this.entryPointId=null,this.maxLevel=0;else{let e=0,t=null;for(const[n,r]of this.nouns.entries()){if(0===r.connections.size)continue;const a=Math.max(...r.connections.keys());a>=e&&(e=a,t=n)}this.entryPointId=t,this.maxLevel=e}return!0}getNouns(){return new Map(this.nouns)}clear(){this.nouns.clear(),this.entryPointId=null,this.maxLevel=0}size(){return this.nouns.size}getDistanceFunction(){return this.distanceFunction}getEntryPointId(){return this.entryPointId}getMaxLevel(){return this.maxLevel}getDimension(){return this.dimension}getConfig(){return{...this.config}}async searchLayer(e,t,n,r){const a=new Set([t.id]),s=new Map;s.set(t.id,this.distanceFunction(e,t.vector));const o=new Map;for(o.set(t.id,this.distanceFunction(e,t.vector));s.size>0;){const[t,i]=[...s][0];s.delete(t);const c=[...o][o.size-1];if(o.size>=n&&i>c[1])break;const u=this.nouns.get(t);if(!u){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const l=u.connections.get(r)||new Set;if(this.useParallelization&&l.size>=10){const t=[];for(const e of l)if(!a.has(e)){a.add(e);const n=this.nouns.get(e);if(!n)continue;t.push({id:e,vector:n.vector})}if(t.length>0){const r=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of r)if((o.size<n||t<c[1])&&(s.set(e,t),o.set(e,t),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}else for(const t of l)if(!a.has(t)){a.add(t);const r=this.nouns.get(t);if(!r)continue;const i=this.distanceFunction(e,r.vector);if((o.size<n||i<c[1])&&(s.set(t,i),o.set(t,i),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}return new Map([...o].sort((e,t)=>e[1]-t[1]))}selectNeighbors(e,t,n){if(t.size<=n)return t;const r=[...t].sort((e,t)=>e[1]-t[1]),a=new Map;for(let e=0;e<Math.min(n,r.length);e++)a.set(r[e][0],r[e][1]);return a}pruneConnections(e,t){const n=e.connections.get(t);if(n.size<=this.config.M)return;const r=new Map,a=new Set;for(const t of n){const n=this.nouns.get(t);n&&(r.set(t,this.distanceFunction(e.vector,n.vector)),a.add(t))}if(0===r.size)return void e.connections.set(t,new Set);const s=this.selectNeighbors(e.vector,r,this.config.M);e.connections.set(t,new Set(s.keys()))}getRandomLevel(){const e=Math.random();return Math.floor(-Math.log(e)*(1/Math.log(this.config.M)))}}const j={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class q{constructor(e=16,t=256){this.centroids=[],this.subvectorSize=0,this.initialized=!1,this.dimension=0,this.numSubvectors=e,this.numCentroids=t}train(e){if(0===e.length)throw new Error("Cannot train product quantizer with empty vector set");this.dimension=e[0].length,this.subvectorSize=Math.ceil(this.dimension/this.numSubvectors);for(let t=0;t<this.numSubvectors;t++){const n=e.map(e=>{const n=t*this.subvectorSize,r=Math.min(n+this.subvectorSize,this.dimension);return e.slice(n,r)});this.centroids[t]=this.kMeansPlusPlus(n,this.numCentroids)}this.initialized=!0}quantize(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=n*this.subvectorSize,a=Math.min(r+this.subvectorSize,this.dimension),s=e.slice(r,a);let o=Number.MAX_VALUE,i=0;for(let e=0;e<this.centroids[n].length;e++){const t=this.centroids[n][e],r=this.euclideanDistanceSquared(s,t);r<o&&(o=r,i=e)}t.push(i)}return t}reconstruct(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.numSubvectors)throw new Error(`Code length mismatch: expected ${this.numSubvectors}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=e[n],a=this.centroids[n][r];for(const e of a)t.push(e)}return t.slice(0,this.dimension)}euclideanDistanceSquared(e,t){let n=0;const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a]-t[a];n+=r*r}return n}kMeansPlusPlus(e,t){if(e.length<t)return[...e];const n=[],r=Math.floor(Math.random()*e.length);n.push([...e[r]]);for(let r=1;r<t;r++){const t=e.map(e=>{let t=Number.MAX_VALUE;for(const r of n){const n=this.euclideanDistanceSquared(e,r);t=Math.min(t,n)}return t}),r=t.reduce((e,t)=>e+t,0);let a=Math.random()*r,s=0;for(let e=0;e<t.length;e++)if(a-=t[e],a<=0){s=e;break}n.push([...e[s]])}return n}getCentroids(){return this.centroids}setCentroids(e){this.centroids=e,this.numSubvectors=e.length,this.numCentroids=e[0].length,this.initialized=!0}getDimension(){return this.dimension}setDimension(e){this.dimension=e,this.subvectorSize=Math.ceil(e/this.numSubvectors)}}class K extends H{constructor(e={},t,n=null){super(e,t),this.productQuantizer=null,this.storage=null,this.useDiskBasedIndex=!1,this.useProductQuantization=!1,this.quantizedVectors=new Map,this.memoryUsage=0,this.vectorCount=0,this.optimizedConfig={...j,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new q(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.useDiskBasedIndex=this.optimizedConfig.useDiskBasedIndex||!1}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");const r=8*n.length+this.optimizedConfig.M*this.optimizedConfig.ml*16;if(this.memoryUsage+=r,this.vectorCount++,this.useProductQuantization&&this.memoryUsage>this.optimizedConfig.memoryThreshold&&this.productQuantizer&&!this.productQuantizer.getDimension()&&this.initializeProductQuantizer(),this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const e=this.productQuantizer.quantize(n);this.quantizedVectors.set(t,e);const r=this.productQuantizer.reconstruct(e);return await super.addItem({id:t,vector:r})}if(this.useDiskBasedIndex&&this.storage){const e={id:t,vector:n,connections:new Map};this.storage.saveNoun(e).catch(e=>{console.error(`Failed to save noun ${t} to storage:`,e)})}return await super.addItem(e)}async search(e,t=10){if(!e)throw new Error("Query vector is undefined or null");if(this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const n=this.productQuantizer.quantize(e),r=this.productQuantizer.reconstruct(n);return await super.search(r,t)}return await super.search(e,t)}removeItem(e){return this.useProductQuantization&&this.quantizedVectors.delete(e),this.useDiskBasedIndex&&this.storage&&this.storage.deleteNoun(e).catch(t=>{console.error(`Failed to delete noun ${e} from storage:`,t)}),this.vectorCount>0&&(this.memoryUsage=Math.max(0,this.memoryUsage-this.memoryUsage/this.vectorCount),this.vectorCount--),super.removeItem(e)}clear(){this.useProductQuantization&&(this.quantizedVectors.clear(),this.productQuantizer=new q(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.memoryUsage=0,this.vectorCount=0,super.clear()}initializeProductQuantizer(){if(!this.productQuantizer)return;const e=super.getNouns(),t=[];for(const[n,r]of e)t.push(r.vector);if(t.length>0){this.productQuantizer.train(t);for(const[t,n]of e){const e=this.productQuantizer.quantize(n.vector);this.quantizedVectors.set(t,e)}console.log(`Initialized product quantizer with ${t.length} vectors`)}}getProductQuantizer(){return this.productQuantizer}getOptimizedConfig(){return{...this.optimizedConfig}}getMemoryUsage(){return this.memoryUsage}setStorage(e){this.storage=e}getStorage(){return this.storage}setUseDiskBasedIndex(e){this.useDiskBasedIndex=e}getUseDiskBasedIndex(){return this.useDiskBasedIndex}setUseProductQuantization(e){this.useProductQuantization=e}getUseProductQuantization(){return this.useProductQuantization}}const X="nouns",Y="verbs",Q="metadata",J="person",Z="place",ee="thing",te="event",ne="concept",re="content",ae="default";class se{constructor(){this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.personDir=null,this.placeDir=null,this.thingDir=null,this.eventDir=null,this.conceptDir=null,this.contentDir=null,this.defaultDir=null,this.isInitialized=!1,this.isAvailable=!1,this.isPersistentRequested=!1,this.isPersistentGranted=!1,this.isAvailable="undefined"!=typeof navigator&&"storage"in navigator&&"getDirectory"in navigator.storage}async init(){if(!this.isInitialized){if(!this.isAvailable)throw new Error("Origin Private File System is not available in this environment");try{const e=await navigator.storage.getDirectory();this.rootDir=await e.getDirectoryHandle("opfs-vector-db",{create:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(X,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(Y,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(Q,{create:!0}),this.personDir=await this.nounsDir.getDirectoryHandle(J,{create:!0}),this.placeDir=await this.nounsDir.getDirectoryHandle(Z,{create:!0}),this.thingDir=await this.nounsDir.getDirectoryHandle(ee,{create:!0}),this.eventDir=await this.nounsDir.getDirectoryHandle(te,{create:!0}),this.conceptDir=await this.nounsDir.getDirectoryHandle(ne,{create:!0}),this.contentDir=await this.nounsDir.getDirectoryHandle(re,{create:!0}),this.defaultDir=await this.nounsDir.getDirectoryHandle(ae,{create:!0}),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize OPFS storage:",e),new Error(`Failed to initialize OPFS storage: ${e}`)}}}isOPFSAvailable(){return this.isAvailable}async requestPersistentStorage(){if(!this.isAvailable)return console.warn("Cannot request persistent storage: OPFS is not available"),!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted||(this.isPersistentGranted=await navigator.storage.persist()),this.isPersistentRequested=!0,this.isPersistentGranted}catch(e){return console.warn("Failed to request persistent storage:",e),!1}}async isPersistent(){if(!this.isAvailable)return!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted}catch(e){return console.warn("Failed to check persistent storage status:",e),!1}}async saveNoun(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodeDirectory(e.id),r=await n.getFileHandle(e.id,{create:!0}),a=await r.createWritable();await a.write(JSON.stringify(t)),await a.close()}catch(t){throw console.error(`Failed to save noun ${e.id}:`,t),new Error(`Failed to save noun ${e.id}: ${t}`)}}async getNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e);try{const n=await t.getFileHandle(e),r=await n.getFile(),a=await r.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch(n){if(t!==this.defaultDir)try{const t=await this.defaultDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(n){const r=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const n of r)if(n!==t)try{const t=await n.getFileHandle(e),r=await t.getFile(),a=await r.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch{}return null}return null}}catch(t){throw console.error(`Failed to get node ${e}:`,t),new Error(`Failed to get node ${e}: ${t}`)}}async getNounsByNounType(e){await this.ensureInitialized();try{const t=[];let n;switch(e){case"person":n=this.personDir;break;case"place":n=this.placeDir;break;case"thing":n=this.thingDir;break;case"event":n=this.eventDir;break;case"concept":n=this.conceptDir;break;case"content":n=this.contentDir;break;default:n=this.defaultDir}try{const e=n.entries();for await(const[n,r]of e)try{if("file"!==r.kind)continue;const e=r,n=await e.getFile(),a=await n.text(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));t.push({id:s.id,vector:s.vector,connections:o})}catch(e){console.warn(`Failed to read node ${n} from directory:`,e)}}catch(t){console.warn(`Failed to read directory for noun type ${e}:`,t)}return t}catch(t){throw console.error(`Failed to get nouns for noun type ${e}:`,t),new Error(`Failed to get nouns for noun type ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNounsByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async deleteNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e);try{return void await t.removeEntry(e)}catch(n){if(t!==this.defaultDir)try{return void await this.defaultDir.removeEntry(e)}catch(n){const r=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const n of r)if(n!==t)try{return void await n.removeEntry(e)}catch{}return}return}}catch(t){throw console.error(`Failed to delete noun ${e}:`,t),new Error(`Failed to delete noun ${e}: ${t}`)}}async saveVerb(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.verbsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save verb ${e.id}:`,t),new Error(`Failed to save verb ${e.id}: ${t}`)}}async getVerb(e){await this.ensureInitialized();try{const t=await this.verbsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch(t){if("NotFoundError"===t.name)return null;throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllEdges(){await this.ensureInitialized();try{const e=[],t=this.verbsDir.entries();for await(const[n,r]of t){if("file"!==r.kind)continue;const t=await this.getVerb(n);t&&e.push(t)}return e}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getAllVerbs(){return this.getAllEdges()}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async deleteVerb(e){return this.deleteEdge(e)}async getEdgesBySource(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getEdgesByTarget(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getEdgesByType(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async getVerbsByType(e){return this.getEdgesByType(e)}async saveMetadata(e,t){await this.ensureInitialized();try{const n=await this.metadataDir.getFileHandle(e,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=await this.metadataDir.getFileHandle(e),n=await t.getFile(),r=await n.text();return JSON.parse(r)}catch(t){if("NotFoundError"===t.name)return null;throw console.error(`Failed to get metadata for ${e}:`,t),new Error(`Failed to get metadata for ${e}: ${t}`)}}async clear(){await this.ensureInitialized();try{await this.rootDir.removeEntry(X,{recursive:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(X,{create:!0}),this.personDir=await this.nounsDir.getDirectoryHandle(J,{create:!0}),this.placeDir=await this.nounsDir.getDirectoryHandle(Z,{create:!0}),this.thingDir=await this.nounsDir.getDirectoryHandle(ee,{create:!0}),this.eventDir=await this.nounsDir.getDirectoryHandle(te,{create:!0}),this.conceptDir=await this.nounsDir.getDirectoryHandle(ne,{create:!0}),this.contentDir=await this.nounsDir.getDirectoryHandle(re,{create:!0}),this.defaultDir=await this.nounsDir.getDirectoryHandle(ae,{create:!0}),await this.rootDir.removeEntry(Y,{recursive:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(Y,{create:!0}),await this.rootDir.removeEntry(Q,{recursive:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(Q,{create:!0})}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async ensureInitialized(){this.isInitialized||await this.init()}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}async getNodeDirectory(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return this.personDir;case"place":return this.placeDir;case"thing":return this.thingDir;case"event":return this.eventDir;case"concept":return this.conceptDir;case"content":return this.contentDir;default:return this.defaultDir}return this.defaultDir}catch(e){return this.defaultDir}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{for await(const[r,a]of e.entries())if("file"===a.kind){n+=(await a.getFile()).size}else"directory"===a.kind&&(n+=await t(a))}catch(e){console.warn("Error calculating size for directory:",e)}return n},n=async e=>{let t=0;try{for await(const[n,r]of e.entries())"file"===r.kind&&t++}catch(e){console.warn("Error counting files in directory:",e)}return t};this.nounsDir&&(e+=await t(this.nounsDir)),this.verbsDir&&(e+=await t(this.verbsDir)),this.metadataDir&&(e+=await t(this.metadataDir));const r=this.personDir?await t(this.personDir):0,a=this.placeDir?await t(this.placeDir):0,s=this.thingDir?await t(this.thingDir):0,o=this.eventDir?await t(this.eventDir):0,i=this.conceptDir?await t(this.conceptDir):0,c=this.contentDir?await t(this.contentDir):0,u=this.defaultDir?await t(this.defaultDir):0;let l=null,d={isPersistent:await this.isPersistent(),nounTypes:{person:{size:r,count:this.personDir?await n(this.personDir):0},place:{size:a,count:this.placeDir?await n(this.placeDir):0},thing:{size:s,count:this.thingDir?await n(this.thingDir):0},event:{size:o,count:this.eventDir?await n(this.eventDir):0},concept:{size:i,count:this.conceptDir?await n(this.conceptDir):0},content:{size:c,count:this.contentDir?await n(this.contentDir):0},default:{size:u,count:this.defaultDir?await n(this.defaultDir):0}}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();l=e.quota||null,d={...d,usage:e.usage,quota:e.quota,freePercentage:e.quota?(e.quota-(e.usage||0))/e.quota*100:null}}}catch(e){console.warn("Unable to get storage estimate:",e)}return{type:"opfs",used:e,quota:l,details:d}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}}class oe{constructor(){this.nouns=new Map,this.verbs=new Map,this.metadata=new Map,this.nouns.set(J,new Map),this.nouns.set(Z,new Map),this.nouns.set(ee,new Map),this.nouns.set(te,new Map),this.nouns.set(ne,new Map),this.nouns.set(re,new Map),this.nouns.set(ae,new Map)}async saveNoun(e){return this.saveNode(e)}async getNoun(e){return this.getNode(e)}async getAllNouns(){return this.getAllNodes()}async getNounsByNounType(e){return this.getNodesByNounType(e)}async deleteNoun(e){return this.deleteNode(e)}async saveVerb(e){return this.saveEdge(e)}async getVerb(e){return this.getEdge(e)}async getAllVerbs(){return this.getAllEdges()}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getVerbsByType(e){return this.getEdgesByType(e)}async deleteVerb(e){return this.deleteEdge(e)}async init(){}async getNodeType(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return J;case"place":return Z;case"thing":return ee;case"event":return te;case"concept":return ne;case"content":return re;default:return ae}return ae}catch(e){return ae}}async saveNode(e){const t={id:e.id,vector:[...e.vector],connections:new Map};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));const n=await this.getNodeType(e.id);this.nouns.get(n).set(e.id,t)}async getNode(e){const t=await this.getNodeType(e);let n=this.nouns.get(t).get(e);if(!n){if(t!==ae){if(n=this.nouns.get(ae).get(e),!n){const r=[J,Z,ee,te,ne,re];for(const a of r){if(a===t)continue;if(n=this.nouns.get(a).get(e),n)break}}}if(!n)return null}const r={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,t]of n.connections.entries())r.connections.set(e,new Set(t));return r}async getNodesByNounType(e){const t=[];let n;switch(e){case"person":n=this.nouns.get(J);break;case"place":n=this.nouns.get(Z);break;case"thing":n=this.nouns.get(ee);break;case"event":n=this.nouns.get(te);break;case"concept":n=this.nouns.get(ne);break;case"content":n=this.nouns.get(re);break;default:n=this.nouns.get(ae)}for(const e of n.keys()){const n=await this.getNode(e);n&&t.push(n)}return t}async getAllNodes(){const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNodesByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}async deleteNode(e){const t=await this.getNodeType(e);if(!this.nouns.get(t).delete(e)&&t!==ae){if(!this.nouns.get(ae).delete(e)){const n=[J,Z,ee,te,ne,re];for(const r of n){if(r===t)continue;if(this.nouns.get(r).delete(e))break}}}}async saveMetadata(e,t){this.metadata.set(e,JSON.parse(JSON.stringify(t)))}async getMetadata(e){const t=this.metadata.get(e);return t?JSON.parse(JSON.stringify(t)):null}async saveEdge(e){const t={id:e.id,vector:[...e.vector],connections:new Map,sourceId:e.sourceId,targetId:e.targetId,type:e.type,weight:e.weight,metadata:e.metadata?JSON.parse(JSON.stringify(e.metadata)):void 0};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.verbs.set(e.id,t)}async getEdge(e){const t=this.verbs.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map,sourceId:t.sourceId,targetId:t.targetId,type:t.type,weight:t.weight,metadata:t.metadata?JSON.parse(JSON.stringify(t.metadata)):void 0};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllEdges(){const e=[];for(const t of this.verbs.keys()){const n=await this.getEdge(t);n&&e.push(n)}return e}async getEdgesBySource(e){const t=[];for(const n of this.verbs.values())if(n.sourceId===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async getEdgesByTarget(e){const t=[];for(const n of this.verbs.values())if(n.targetId===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async getEdgesByType(e){const t=[];for(const n of this.verbs.values())if(n.type===e){const e=await this.getEdge(n.id);e&&t.push(e)}return t}async deleteEdge(e){this.verbs.delete(e)}async clear(){const e=[J,Z,ee,te,ne,re,ae];for(const t of e){this.nouns.get(t).clear()}this.verbs.clear(),this.metadata.clear()}async getStorageStatus(){try{let e=0;const t=e=>{if(null==e)return 0;const n=typeof e;if("number"===n)return 8;if("string"===n)return 2*e.length;if("boolean"===n)return 4;if(Array.isArray(e))return e.reduce((e,n)=>e+t(n),0);if("object"===n){if(e instanceof Map){let n=0;for(const[r,a]of e.entries())n+=t(r)+t(a);return n}if(e instanceof Set){let n=0;for(const r of e)n+=t(r);return n}return Object.entries(e).reduce((e,[n,r])=>e+2*n.length+t(r),0)}return 0},n={},r=[J,Z,ee,te,ne,re,ae];let a=0,s=0;for(const e of r){const r=this.nouns.get(e);let o=0;for(const e of r.values())o+=t(e);n[e]={size:o,count:r.size},s+=o,a+=r.size}e+=s;let o=0;for(const e of this.verbs.values())o+=t(e);e+=o;let i=0;for(const e of this.metadata.values())i+=t(e);e+=i;let c=null,u={nodeCount:a,edgeCount:this.verbs.size,metadataCount:this.metadata.size,nounTypes:n,nodesSize:s,edgesSize:o,metadataSize:i};if("undefined"!=typeof window&&window.performance&&window.performance.memory){const e=window.performance.memory;c=e.jsHeapSizeLimit,u={...u,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}return{type:"memory",used:e,quota:c,details:u}}catch(e){return console.error("Failed to get memory storage status:",e),{type:"memory",used:0,quota:null,details:{error:String(e)}}}}}async function ie(e={}){const t="undefined"!=typeof window,n="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;"undefined"!=typeof window||"undefined"!=typeof process&&process.versions&&process.versions.node;if(e.forceMemoryStorage)return console.log("Using in-memory storage (forced by configuration)"),new oe;const r={bucketName:void 0,accountId:void 0,accessKeyId:void 0,secretAccessKey:void 0,region:void 0,endpoint:void 0};if(e.r2Storage||e.s3Storage||e.gcsStorage||e.customS3Storage||n&&(process.env.R2_BUCKET_NAME||process.env.S3_BUCKET_NAME||process.env.GCS_BUCKET_NAME))try{const t=n?{bucketName:process.env.R2_BUCKET_NAME,accountId:process.env.R2_ACCOUNT_ID,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY}:r,a=n?{bucketName:process.env.S3_BUCKET_NAME,accessKeyId:process.env.S3_ACCESS_KEY_ID||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY||process.env.AWS_SECRET_ACCESS_KEY,region:process.env.S3_REGION||process.env.AWS_REGION}:r,s=n?{bucketName:process.env.GCS_BUCKET_NAME,accessKeyId:process.env.GCS_ACCESS_KEY_ID,secretAccessKey:process.env.GCS_SECRET_ACCESS_KEY,endpoint:process.env.GCS_ENDPOINT}:r,o={...e,r2Storage:e.r2Storage?{...t,...e.r2Storage}:t.bucketName&&t.accessKeyId&&t.secretAccessKey?t:void 0,s3Storage:e.s3Storage?{...a,...e.s3Storage}:a.bucketName&&a.accessKeyId&&a.secretAccessKey?a:void 0,gcsStorage:e.gcsStorage?{...s,...e.gcsStorage}:s.bucketName&&s.accessKeyId&&s.secretAccessKey?s:void 0},i=await Promise.resolve().then(function(){return Fe});if(o.r2Storage&&o.r2Storage.bucketName&&o.r2Storage.accountId&&o.r2Storage.accessKeyId&&o.r2Storage.secretAccessKey)return console.log("Using Cloudflare R2 storage"),new i.R2Storage({bucketName:o.r2Storage.bucketName,accountId:o.r2Storage.accountId,accessKeyId:o.r2Storage.accessKeyId,secretAccessKey:o.r2Storage.secretAccessKey,serviceType:"r2"});if(o.s3Storage&&o.s3Storage.bucketName&&o.s3Storage.accessKeyId&&o.s3Storage.secretAccessKey)return console.log("Using Amazon S3 storage"),new i.S3CompatibleStorage({bucketName:o.s3Storage.bucketName,accessKeyId:o.s3Storage.accessKeyId,secretAccessKey:o.s3Storage.secretAccessKey,region:o.s3Storage.region,serviceType:"s3"});if(o.gcsStorage&&o.gcsStorage.bucketName&&o.gcsStorage.accessKeyId&&o.gcsStorage.secretAccessKey)return console.log("Using Google Cloud Storage"),new i.S3CompatibleStorage({bucketName:o.gcsStorage.bucketName,accessKeyId:o.gcsStorage.accessKeyId,secretAccessKey:o.gcsStorage.secretAccessKey,endpoint:o.gcsStorage.endpoint,serviceType:"gcs"});if(o.customS3Storage&&o.customS3Storage.bucketName&&o.customS3Storage.accessKeyId&&o.customS3Storage.secretAccessKey)return console.log("Using custom S3-compatible storage"),new i.S3CompatibleStorage({bucketName:o.customS3Storage.bucketName,accessKeyId:o.customS3Storage.accessKeyId,secretAccessKey:o.customS3Storage.secretAccessKey,endpoint:o.customS3Storage.endpoint,region:o.customS3Storage.region,serviceType:"custom"})}catch(e){console.warn("Failed to load S3CompatibleStorage, falling back to environment-specific storage:",e)}if(t){if(!e.forceFileSystemStorage)try{const t=new se;if(t.isOPFSAvailable()){if(e.requestPersistentStorage){await t.requestPersistentStorage()?console.log("Persistent storage permission granted"):console.warn("Persistent storage permission denied")}return console.log("Using Origin Private File System (OPFS) storage"),t}}catch(e){console.warn("OPFS storage initialization failed:",e)}return console.log("Using in-memory storage for browser environment"),new oe}if(!n)return console.log("Using in-memory storage for serverless/unknown environment"),new oe;try{const e=await Promise.resolve().then(function(){return ke});return console.log("Using file system storage for Node.js environment"),new e.FileSystemStorage}catch(e){return console.warn("Failed to load FileSystemStorage:",e),console.log("Using in-memory storage for Node.js environment"),new oe}}const ce={Person:"person",Place:"place",Thing:"thing",Event:"event",Concept:"concept",Content:"content",Group:"group",List:"list",Category:"category"},ue={AttributedTo:"attributedTo",Controls:"controls",Created:"created",Earned:"earned",Owns:"owns",MemberOf:"memberOf",RelatedTo:"relatedTo",WorksWith:"worksWith",FriendOf:"friendOf",ReportsTo:"reportsTo",Supervises:"supervises",Mentors:"mentors",Follows:"follows",Likes:"likes"};var le;!function(e){e.SENSE="sense",e.CONDUIT="conduit",e.COGNITION="cognition",e.MEMORY="memory",e.PERCEPTION="perception",e.DIALOG="dialog",e.ACTIVATION="activation",e.WEBSOCKET="webSocket"}(le||(le={}));class de{constructor(e){this.description="Base conduit augmentation",this.enabled=!0,this.isInitialized=!1,this.connections=new Map,this.name=e}async initialize(){if(!this.isInitialized)try{this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){for(const[e,t]of this.connections.entries())try{t.close&&await t.close()}catch(t){console.error(`Failed to close connection ${e}:`,t)}this.connections.clear(),this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}class he extends de{constructor(e="websocket-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebSockets",this.webSocketConnections=new Map,this.messageCallbacks=new Map}getType(){return le.CONDUIT}async establishConnection(e,t){await this.ensureInitialized();try{const n=e,r=t.protocols,a=await this.connectWebSocket(n,r);return this.connections.set(a.connectionId,a),{success:!0,data:a}}catch(t){return console.error(`Failed to establish connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish connection: ${t}`}}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=v(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`WebSocket connection ${e} not found`);if(!n.send)throw new Error(`WebSocket connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`WebSocket connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`WebSocket connection ${e} not found`);if(!r.close)throw new Error(`WebSocket connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}class pe extends de{constructor(e="webrtc-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebRTC",this.peerConnections=new Map,this.dataChannels=new Map,this.webSocketConnections=new Map,this.messageCallbacks=new Map,this.signalServer=null}getType(){return le.CONDUIT}async initialize(){if(!this.isInitialized)try{if("undefined"==typeof RTCPeerConnection)throw new Error("WebRTC is not available in this environment");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async establishConnection(e,t){await this.ensureInitialized();try{!this.signalServer&&t.signalServerUrl&&(this.signalServer=await this.connectWebSocket(t.signalServerUrl),await this.onWebSocketMessage(this.signalServer.connectionId,async e=>{const n=e;if("ice-candidate"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.addIceCandidate(new RTCIceCandidate(n.candidate))}catch(e){console.error("Failed to add ICE candidate:",e)}}else if("offer"===n.type&&n.targetPeerId===t.localPeerId)await this.handleOffer(n.sourcePeerId,n.offer,t);else if("answer"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.setRemoteDescription(new RTCSessionDescription(n.answer))}catch(e){console.error("Failed to set remote description:",e)}}}));const n=new RTCPeerConnection({iceServers:t.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),r=v();this.peerConnections.set(e,n);const a=n.createDataChannel("brainy-sync",{ordered:!0});a.onopen=()=>{console.log(`Data channel to ${e} opened`)},a.onclose=()=>{console.log(`Data channel to ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},a.onerror=e=>{console.error("Data channel error:",e)};const s=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}s(t)}catch(e){console.error("Error handling WebRTC message:",e)}},this.dataChannels.set(e,a),n.onicecandidate=n=>{n.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:t.localPeerId,targetPeerId:e,candidate:n.candidate})};const o={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async t=>{const n=this.dataChannels.get(e);if(!n||"open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof t||t instanceof Blob?n.send(t):t instanceof ArrayBuffer?n.send(new Uint8Array(t)):ArrayBuffer.isView(t)?n.send(t):n.send(JSON.stringify(t))},close:async()=>{const t=this.dataChannels.get(e);t&&t.close();const n=this.peerConnections.get(e);n&&n.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:s};this.webSocketConnections.set(r,o),this.messageCallbacks.set(r,new Set);const i=await n.createOffer();return await n.setLocalDescription(i),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"offer",sourcePeerId:t.localPeerId,targetPeerId:e,offer:i}),{success:!0,data:o}}catch(t){return console.error(`Failed to establish WebRTC connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish WebRTC connection: ${t}`}}}async handleOffer(e,t,n){try{let r=this.peerConnections.get(e);r||(r=new RTCPeerConnection({iceServers:n.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),this.peerConnections.set(e,r),r.onicecandidate=t=>{t.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:n.localPeerId,targetPeerId:e,candidate:t.candidate})},r.ondatachannel=t=>{const n=t.channel,r=v();this.dataChannels.set(e,n),n.onopen=()=>{console.log(`Data channel from ${e} opened`)},n.onclose=()=>{console.log(`Data channel from ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},n.onerror=e=>{console.error("Data channel error:",e)};const a=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};n.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}a(t)}catch(e){console.error("Error handling WebRTC message:",e)}};const s={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async e=>{if("open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof e||e instanceof Blob?n.send(e):e instanceof ArrayBuffer?n.send(new Uint8Array(e)):ArrayBuffer.isView(e)?n.send(e):n.send(JSON.stringify(e))},close:async()=>{n.close();const t=this.peerConnections.get(e);t&&t.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:a};this.webSocketConnections.set(r,s),this.messageCallbacks.set(r,new Set)}),await r.setRemoteDescription(new RTCSessionDescription(t));const a=await r.createAnswer();await r.setLocalDescription(a),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"answer",sourcePeerId:n.localPeerId,targetPeerId:e,answer:a})}catch(e){throw console.error("Failed to handle WebRTC offer:",e),new Error(`Failed to handle WebRTC offer: ${e}`)}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:v(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=v(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`Connection ${e} not found`);if(!n.send)throw new Error(`Connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`Connection ${e} not found`);if(!r.close)throw new Error(`Connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}async function fe(e,t,n={}){switch(e){case"websocket":const n=new he(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new pe(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class me extends he{constructor(e="server-search-conduit"){super(e),this.localDb=null}async initialize(){if(!this.isInitialized)try{if(await super.initialize(),!this.localDb)throw new Error("Local database not set. Call setLocalDb before initializing.");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}setLocalDb(e){this.localDb=e}getLocalDb(){return this.localDb}async searchServer(e,t,n=10){await this.ensureInitialized();try{const r=await this.readData({connectionId:e,query:{type:"search",query:t,limit:n}});if(r.success&&r.data){const e=r.data;if(this.localDb)for(const t of e){await this.localDb.get(t.id)||await this.localDb.add(t.vector,t.metadata)}return{success:!0,data:e}}return{success:!1,data:null,error:r.error||"Unknown error searching server"}}catch(e){return console.error("Error searching server:",e),{success:!1,data:null,error:`Error searching server: ${e}`}}}async searchLocal(e,t=10){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:null,error:"Local database not initialized"};return{success:!0,data:await this.localDb.searchText(e,t)}}catch(e){return console.error("Error searching local database:",e),{success:!1,data:null,error:`Error searching local database: ${e}`}}}async searchCombined(e,t,n=10){await this.ensureInitialized();try{const r=await this.searchLocal(t,n);if(!r.success)return r;const a=r.data;if(a.length>=n)return r;const s=await this.searchServer(e,t,n-a.length);if(!s.success)return r;const o=s.data,i=[...a],c=new Set(a.map(e=>e.id));for(const e of o)c.has(e.id)||i.push(e);return{success:!0,data:i}}catch(e){return console.error("Error performing combined search:",e),{success:!1,data:null,error:`Error performing combined search: ${e}`}}}async addToBoth(e,t,n={}){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:"",error:"Local database not initialized"};const r=await this.localDb.add(t,n),a=await this.localDb.get(r);if(!a)return{success:!1,data:"",error:"Failed to retrieve newly created noun"};const s=await this.writeData({connectionId:e,data:{type:"addNoun",vector:a.vector,metadata:a.metadata}});return s.success?{success:!0,data:r}:{success:!0,data:r,error:`Added locally but failed to add to server: ${s.error}`}}catch(e){return console.error("Error adding data to both:",e),{success:!1,data:"",error:`Error adding data to both: ${e}`}}}}class ge{constructor(e="server-search-activation"){this.enabled=!0,this.isInitialized=!1,this.conduitAugmentation=null,this.connections=new Map,this.name=e,this.description="Activation augmentation for server-hosted Brainy search"}getType(){return le.ACTIVATION}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}setConduitAugmentation(e){this.conduitAugmentation=e}storeConnection(e,t){this.connections.set(e,t)}getConnection(e){return this.connections.get(e)}triggerAction(e,t){if(!this.conduitAugmentation)return{success:!1,data:null,error:"Conduit augmentation not set"};switch(e){case"connectToServer":return this.handleConnectToServer(t||{});case"searchServer":return this.handleSearchServer(t||{});case"searchLocal":return this.handleSearchLocal(t||{});case"searchCombined":return this.handleSearchCombined(t||{});case"addToBoth":return this.handleAddToBoth(t||{});default:return{success:!1,data:null,error:`Unknown action: ${e}`}}}handleConnectToServer(e){const t=e.serverUrl,n=e.protocols;return t?{success:!0,data:this.conduitAugmentation.establishConnection(t,{protocols:n})}:{success:!1,data:null,error:"serverUrl parameter is required"}}handleSearchServer(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchServer(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleSearchLocal(e){const t=e.query,n=e.limit||10;return t?{success:!0,data:this.conduitAugmentation.searchLocal(t,n)}:{success:!1,data:null,error:"query parameter is required"}}handleSearchCombined(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchCombined(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleAddToBoth(e){const t=e.connectionId,n=e.data,r=e.metadata||{};return t?n?{success:!0,data:this.conduitAugmentation.addToBoth(t,n,r)}:{success:!1,data:null,error:"data parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}generateOutput(e,t){return{success:!1,data:"",error:"generateOutput is not implemented for ServerSearchActivationAugmentation"}}interactExternal(e,t){return{success:!1,data:null,error:"interactExternal is not implemented for ServerSearchActivationAugmentation"}}}async function ye(e,t={}){const n=new me(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new ge(t.activationName);await r.initialize(),r.setConduitAugmentation(n);const a=await n.establishConnection(e,{protocols:t.protocols});if(!a.success||!a.data)throw new Error(`Failed to connect to server: ${a.error}`);const s=a.data;return r.storeConnection(s.connectionId,s),{conduit:n,activation:r,connection:s}}class be{constructor(e={}){this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,this.distanceFunction=e.distanceFunction||I,e.hnswOptimized?(this.index=new K(e.hnswOptimized,this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0):this.index=new H(e.hnsw,this.distanceFunction),this.storage=e.storageAdapter||null,this.embeddingFunction=e.embeddingFunction||B,this.requestPersistentStorage=e.storage?.requestPersistentStorage||!1,this.readOnly=e.readOnly||!1,this.storageConfig=e.storage||{},e.remoteServer&&(this.remoteServerConfig=e.remoteServer)}checkReadOnly(){if(this.readOnly)throw new Error("Cannot perform write operation: database is in read-only mode")}async init(){if(!this.isInitialized&&!this.isInitializing){this.isInitializing=!0;try{try{console.log("Pre-loading Universal Sentence Encoder model..."),await this.embeddingFunction(""),console.log("Universal Sentence Encoder model loaded successfully")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e),console.log("Retrying Universal Sentence Encoder initialization...");try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return U}),t=e();await t(""),console.log("Successfully loaded Universal Sentence Encoder with fallback method"),this.embeddingFunction=t}catch(e){console.error("All attempts to load Universal Sentence Encoder failed:",e)}}if(!this.storage){const e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};this.storage=await ie(e)}await this.storage.init(),this.useOptimizedIndex&&this.index instanceof K&&this.index.setStorage(this.storage);const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)await this.index.addItem({id:t.id,vector:t.vector});if(this.remoteServerConfig&&this.remoteServerConfig.autoConnect)try{await this.connectToRemoteServer(this.remoteServerConfig.url,this.remoteServerConfig.protocols)}catch(e){console.warn("Failed to auto-connect to remote server:",e)}this.isInitialized=!0,this.isInitializing=!1}catch(e){throw console.error("Failed to initialize BrainyData:",e),this.isInitializing=!1,new Error(`Failed to initialize BrainyData: ${e}`)}}}async connectToRemoteServer(e,t){await this.ensureInitialized();try{const{conduit:n,connection:r}=await ye(e,{protocols:t,localDb:this});return this.serverSearchConduit=n,this.serverConnection=r,r}catch(e){throw console.error("Failed to connect to remote server:",e),new Error(`Failed to connect to remote server: ${e}`)}}async add(e,t,n={}){await this.ensureInitialized(),this.checkReadOnly();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize data: ${e}`)}if(!r)throw new Error("Vector is undefined or null");const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:v());await this.index.addItem({id:a,vector:r});const s=this.index.getNouns().get(a);if(!s)throw new Error(`Failed to retrieve newly created noun with ID ${a}`);if(await this.storage.saveNoun(s),void 0!==t){if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(ce).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ce.Concept)}await this.storage.saveMetadata(a,t)}if(n.addToRemote&&this.isConnectedToRemoteServer())try{await this.addToRemote(a,r,t)}catch(e){console.warn(`Failed to add to remote server: ${e}. Continuing with local add.`)}return a}catch(e){throw console.error("Failed to add vector:",e),new Error(`Failed to add vector: ${e}`)}}async addToBoth(e,t,n={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.add(e,t,{...n,addToRemote:!0})}async addToRemote(e,t,n){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const e=await this.serverSearchConduit.addToBoth(this.serverConnection.connectionId,t,n);if(!e.success)throw new Error(`Remote add failed: ${e.error}`);return!0}catch(e){throw console.error("Failed to add to remote server:",e),new Error(`Failed to add to remote server: ${e}`)}}async addBatch(e,t={}){await this.ensureInitialized(),this.checkReadOnly(),t.concurrency;const n=t.batchSize||50;try{const r=[],a=[...e];for(;a.length>0;){const e=a.splice(0,n),s=[],o=[];e.forEach((e,n)=>{if(Array.isArray(e.vectorOrData)&&e.vectorOrData.every(e=>"number"==typeof e)&&!t.forceEmbed)s.push({vectorOrData:e.vectorOrData,metadata:e.metadata,index:n});else if("string"==typeof e.vectorOrData)o.push({text:e.vectorOrData,metadata:e.metadata,index:n});else{const t=String(e.vectorOrData);o.push({text:t,metadata:e.metadata,index:n})}});const i=s.map(e=>this.add(e.vectorOrData,e.metadata,t));let c=[];if(o.length>0){const e=o.map(e=>e.text),n=await W(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const u=await Promise.all([...i,...c]);r.push(...u)}return r}catch(e){throw console.error("Failed to add batch of items:",e),new Error(`Failed to add batch of items: ${e}`)}}async addBatchToBoth(e,t={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.addBatch(e,{...t,addToRemote:!0})}async searchByNounTypes(e,t=10,n=null,r={}){await this.ensureInitialized();try{let a;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!r.forceEmbed)a=e;else try{a=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}if(!a)throw new Error("Query vector is undefined or null");if(n&&0!==n.length){const e=n.map(e=>this.storage.getNounsByNounType(e)),r=await Promise.all(e),s=[];for(const e of r)s.push(...e);const o=[];for(const e of s){const t=this.index.getDistanceFunction()(a,e.vector);o.push([e.id,t])}o.sort((e,t)=>e[1]-t[1]);const i=o.slice(0,t),c=[];for(const[e,t]of i){const n=s.find(t=>t.id===e);if(!n)continue;const r=await this.storage.getMetadata(e);c.push({id:e,score:t,vector:n.vector,metadata:r})}return c}{const e=await this.index.search(a,t),n=[];for(const[t,r]of e){const e=this.index.getNouns().get(t);if(!e)continue;const a=await this.storage.getMetadata(t);n.push({id:t,score:r,vector:e.vector,metadata:a})}return n}}catch(e){throw console.error("Failed to search vectors by noun types:",e),new Error(`Failed to search vectors by noun types: ${e}`)}}async search(e,t=10,n={}){if(n.searchVerbs){return(await this.searchVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes})).map(e=>({id:e.id,score:e.similarity,vector:e.embedding||[],metadata:{verb:e.verb,source:e.source,target:e.target,...e.data}}))}return n.searchConnectedNouns?this.searchNounsByVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes,direction:n.verbDirection}):"local"===n.searchMode?this.searchLocal(e,t,n):"remote"===n.searchMode?this.searchRemote(e,t,n):"combined"===n.searchMode?this.searchCombined(e,t,n):this.searchLocal(e,t,n)}async searchLocal(e,t=10,n={}){let r,a=e;if("string"!=typeof e||n.forceEmbed||(a=await this.embed(e),n.forceEmbed=!1),r=n.nounTypes&&n.nounTypes.length>0?await this.searchByNounTypes(a,t,n.nounTypes,{forceEmbed:n.forceEmbed}):await this.searchByNounTypes(a,t,null,{forceEmbed:n.forceEmbed}),n.includeVerbs&&this.storage)for(const e of r)try{const t=await this.storage.getVerbsBySource(e.id),n=await this.storage.getVerbsByTarget(e.id),r=[...t,...n];e.metadata||(e.metadata={}),e.metadata.associatedVerbs=r}catch(t){console.warn(`Failed to retrieve verbs for noun ${e.id}:`,t)}return r}async findSimilar(e,t={}){await this.ensureInitialized();const n=await this.get(e);if(!n)throw new Error(`Entity with ID ${e} not found`);const r=(t.limit||10)+1;return(await this.search(n.vector,r,{forceEmbed:!1,nounTypes:t.nounTypes,includeVerbs:t.includeVerbs,searchMode:t.searchMode})).filter(t=>t.id!==e).slice(0,t.limit||10)}async get(e){await this.ensureInitialized();try{const t=this.index.getNouns().get(e);if(!t)return null;const n=await this.storage.getMetadata(e);return{id:e,vector:t.vector,metadata:n}}catch(t){throw console.error(`Failed to get vector ${e}:`,t),new Error(`Failed to get vector ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=this.index.getNouns(),t=[];for(const[n,r]of e.entries()){const e=await this.storage.getMetadata(n);t.push({id:n,vector:r.vector,metadata:e})}return t}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async delete(e){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.removeItem(e))return!1;await this.storage.deleteNoun(e);try{await this.storage.saveMetadata(e,null)}catch(e){}return!0}catch(t){throw console.error(`Failed to delete vector ${e}:`,t),new Error(`Failed to delete vector ${e}: ${t}`)}}async updateMetadata(e,t){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.getNouns().get(e))return!1;if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(ce).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ce.Concept)}return await this.storage.saveMetadata(e,t),!0}catch(t){throw console.error(`Failed to update metadata for vector ${e}:`,t),new Error(`Failed to update metadata for vector ${e}: ${t}`)}}async relate(e,t,n,r){return this.addVerb(e,t,void 0,{type:n,metadata:r})}async addVerb(e,t,n,r={}){await this.ensureInitialized(),this.checkReadOnly();try{const a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a)throw new Error(`Source noun with ID ${e} not found`);if(!s)throw new Error(`Target noun with ID ${t} not found`);const o=r.id||v();let i;if(!r.metadata||n&&!r.forceEmbed)if(n)i=n;else{if(!a.vector||!s.vector||0===a.vector.length||0===s.vector.length||a.vector.length!==s.vector.length)throw new Error("Cannot average vectors: source or target vector is invalid or dimensions don't match");i=a.vector.map((e,t)=>(e+s.vector[t])/2)}else try{let e;e="string"==typeof r.metadata?r.metadata:r.metadata.description&&"string"==typeof r.metadata.description?r.metadata.description:JSON.stringify(r.metadata),"string"!=typeof e&&(e=String(e)),i=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize verb metadata: ${e}`)}let c=r.type;if(c){Object.values(ue).includes(c)||(console.warn(`Invalid verb type: ${c}. Using RelatedTo as default.`),c=ue.RelatedTo)}const u={id:o,vector:i,connections:new Map,sourceId:e,targetId:t,type:c,weight:r.weight,metadata:r.metadata};await this.index.addItem({id:o,vector:i});const l=this.index.getNouns().get(o);if(!l)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);return u.connections=l.connections,await this.storage.saveVerb(u),o}catch(e){throw console.error("Failed to add verb:",e),new Error(`Failed to add verb: ${e}`)}}async getVerb(e){await this.ensureInitialized();try{return await this.storage.getVerb(e)}catch(t){throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllVerbs(){await this.ensureInitialized();try{return await this.storage.getAllVerbs()}catch(e){throw console.error("Failed to get all verbs:",e),new Error(`Failed to get all verbs: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return await this.storage.getVerbsBySource(e)}catch(t){throw console.error(`Failed to get verbs by source ${e}:`,t),new Error(`Failed to get verbs by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return await this.storage.getVerbsByTarget(e)}catch(t){throw console.error(`Failed to get verbs by target ${e}:`,t),new Error(`Failed to get verbs by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return await this.storage.getVerbsByType(e)}catch(t){throw console.error(`Failed to get verbs by type ${e}:`,t),new Error(`Failed to get verbs by type ${e}: ${t}`)}}async deleteVerb(e){await this.ensureInitialized(),this.checkReadOnly();try{return!!this.index.removeItem(e)&&(await this.storage.deleteVerb(e),!0)}catch(t){throw console.error(`Failed to delete verb ${e}:`,t),new Error(`Failed to delete verb ${e}: ${t}`)}}async clear(){await this.ensureInitialized(),this.checkReadOnly();try{this.index.clear(),await this.storage.clear()}catch(e){throw console.error("Failed to clear vector database:",e),new Error(`Failed to clear vector database: ${e}`)}}size(){return this.index.size()}isReadOnly(){return this.readOnly}setReadOnly(e){this.readOnly=e}async embed(e){await this.ensureInitialized();try{return await this.embeddingFunction(e)}catch(e){throw console.error("Failed to embed data:",e),new Error(`Failed to embed data: ${e}`)}}async searchVerbs(e,t=10,n={}){await this.ensureInitialized();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}let a=[];if(n.verbTypes&&n.verbTypes.length>0){const e=n.verbTypes.map(e=>this.getVerbsByType(e)),t=await Promise.all(e);for(const e of t)a.push(...e)}else a=await this.storage.getAllVerbs();a=a.filter(e=>e.embedding&&e.embedding.length>0);const s=[];for(const e of a)if(e.embedding){const t=this.index.getDistanceFunction()(r,e.embedding);s.push({...e,similarity:t})}return s.sort((e,t)=>e.similarity-t.similarity),s.slice(0,t)}catch(e){throw console.error("Failed to search verbs:",e),new Error(`Failed to search verbs: ${e}`)}}async searchNounsByVerbs(e,t=10,n={}){await this.ensureInitialized();try{const r=await this.searchByNounTypes(e,2*t,null,{forceEmbed:n.forceEmbed});if(!n.verbTypes||0===n.verbTypes.length)return r.slice(0,t);const a=new Set,s=n.direction||"both";for(const e of r){let t=[];if("outgoing"===s||"both"===s){const n=await this.storage.getVerbsBySource(e.id);t.push(...n)}if("incoming"===s||"both"===s){const n=await this.storage.getVerbsByTarget(e.id);t.push(...n)}n.verbTypes&&n.verbTypes.length>0&&(t=t.filter(e=>e.verb&&n.verbTypes.includes(e.verb)));for(const n of t)n.source&&n.source!==e.id&&a.add(n.source),n.target&&n.target!==e.id&&a.add(n.target)}const o=[];for(const t of a)try{const r=this.index.getNouns().get(t);if(r){const a=await this.storage.getMetadata(t);let s;s=Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed?e:await this.embeddingFunction(e);const i=this.index.getDistanceFunction()(s,r.vector);o.push({id:t,score:i,vector:r.vector,metadata:a})}}catch(e){console.warn(`Failed to retrieve noun ${t}:`,e)}return o.sort((e,t)=>e.score-t.score),o.slice(0,t)}catch(e){throw console.error("Failed to search nouns by verbs:",e),new Error(`Failed to search nouns by verbs: ${e}`)}}async searchText(e,t=10,n={}){await this.ensureInitialized();try{const r=await this.embed(e);return await this.search(r,t,{nounTypes:n.nounTypes,includeVerbs:n.includeVerbs,searchMode:n.searchMode})}catch(e){throw console.error("Failed to search with text query:",e),new Error(`Failed to search with text query: ${e}`)}}async searchRemote(e,t=10,n={}){if(await this.ensureInitialized(),!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");try{let n;if(n="string"==typeof e?e:"vector-query",!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const r=await this.serverSearchConduit.searchServer(this.serverConnection.connectionId,n,t);if(!r.success)throw new Error(`Remote search failed: ${r.error}`);return r.data}catch(e){throw console.error("Failed to search remote server:",e),new Error(`Failed to search remote server: ${e}`)}}async searchCombined(e,t=10,n={}){if(await this.ensureInitialized(),!this.isConnectedToRemoteServer())return this.searchLocal(e,t,n);try{if(!1!==n.localFirst){const r=await this.searchLocal(e,t,n);if(r.length>=t)return r;const a=await this.searchRemote(e,t-r.length,{...n,storeResults:!0}),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}{const r=await this.searchRemote(e,t,{...n,storeResults:!0});if(r.length>=t)return r;const a=await this.searchLocal(e,t-r.length,n),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}}catch(e){throw console.error("Failed to perform combined search:",e),new Error(`Failed to perform combined search: ${e}`)}}isConnectedToRemoteServer(){return!(!this.serverSearchConduit||!this.serverConnection)}async disconnectFromRemoteServer(){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");return await this.serverSearchConduit.closeWebSocket(this.serverConnection.connectionId),this.serverSearchConduit=null,this.serverConnection=null,!0}catch(e){throw console.error("Failed to disconnect from remote server:",e),new Error(`Failed to disconnect from remote server: ${e}`)}}async ensureInitialized(){if(!this.isInitialized)if(this.isInitializing){let e=0;const t=100,n=50;for(;this.isInitializing&&!this.isInitialized&&e<t;)await new Promise(e=>setTimeout(e,n)),e++;this.isInitialized||await this.init()}else await this.init()}async status(){if(await this.ensureInitialized(),!this.storage)return{type:"any",used:0,quota:null,details:{error:"Storage not initialized"}};try{if("function"!=typeof this.storage.getStorageStatus){return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:"Storage adapter does not implement getStorageStatus method",storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}const e=await this.storage.getStorageStatus();let t={indexSize:this.size()};if(this.useOptimizedIndex&&this.index instanceof K){const e=this.index;t={...t,optimized:!0,memoryUsage:e.getMemoryUsage(),productQuantization:e.getUseProductQuantization(),diskBasedIndex:e.getUseDiskBasedIndex()}}else t.optimized=!1;return{type:e.type||"any",used:e.used||0,quota:e.quota||null,details:{...e.details||{},index:t}}}catch(e){console.error("Failed to get storage status:",e);return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:String(e),storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}}async shutDown(){try{this.isConnectedToRemoteServer()&&await this.disconnectFromRemoteServer(),_(),this.isInitialized=!1}catch(e){throw console.error("Failed to shut down BrainyData:",e),new Error(`Failed to shut down BrainyData: ${e}`)}}async backup(){await this.ensureInitialized();try{const e=await this.getAllNouns(),t=await this.getAllVerbs(),n=Object.values(ce),r=Object.values(ue),a={entryPointId:this.index.getEntryPointId(),maxLevel:this.index.getMaxLevel(),dimension:this.index.getDimension(),config:this.index.getConfig(),connections:{}},s=this.index.getNouns();for(const[e,t]of s.entries()){a.connections[e]={};for(const[n,r]of t.connections.entries())a.connections[e][n]=Array.from(r)}return{nouns:e,verbs:t,nounTypes:n,verbTypes:r,hnswIndex:a,version:"1.0.0"}}catch(e){throw console.error("Failed to backup data:",e),new Error(`Failed to backup data: ${e}`)}}async importSparseData(e,t={}){return this.restore(e,t)}async restore(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(t.clearExisting&&await this.clear(),!(e&&e.nouns&&e.verbs&&e.version))throw new Error("Invalid restore data format");e.nounTypes&&console.log(`Found ${e.nounTypes.length} noun types in restore data`),e.verbTypes&&console.log(`Found ${e.verbTypes.length} verb types in restore data`),e.hnswIndex&&console.log("Found HNSW index data in backup");let n=0;for(const t of e.nouns)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.add(t.vector,t.metadata,{id:t.id}),n++}catch(e){console.error(`Failed to restore noun ${t.id}:`,e)}let r=0;for(const t of e.verbs)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.addVerb(t.sourceId,t.targetId,t.vector,{id:t.id,type:t.metadata?.verb||ue.RelatedTo,metadata:t.metadata}),r++}catch(e){console.error(`Failed to restore verb ${t.id}:`,e)}if(e.hnswIndex&&n>0)try{console.log("Reconstructing HNSW index from backup data..."),this.index=new H(e.hnswIndex.config,this.distanceFunction);for(const t of e.nouns)t.vector&&t.vector.length>0&&await this.index.addItem({id:t.id,vector:t.vector});console.log("HNSW index reconstruction complete")}catch(e){console.error("Failed to reconstruct HNSW index:",e),console.log("Continuing with standard restore process...")}return{nounsRestored:n,verbsRestored:r}}catch(e){throw console.error("Failed to restore data:",e),new Error(`Failed to restore data: ${e}`)}}async generateRandomGraph(e={}){await this.ensureInitialized(),this.checkReadOnly();const t=e.nounCount||10,n=e.verbCount||20,r=e.nounTypes||Object.values(ce),a=e.verbTypes||Object.values(ue);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[ce.Person]:"A person with unique characteristics",[ce.Place]:"A location with specific attributes",[ce.Thing]:"An object with distinct properties",[ce.Event]:"An occurrence with temporal aspects",[ce.Concept]:"An abstract idea or notion",[ce.Content]:"A piece of content or information",[ce.Group]:"A collection of related entities",[ce.List]:"An ordered sequence of items",[ce.Category]:"A classification or grouping"};for(let n=0;n<t;n++){const t=r[Math.floor(Math.random()*r.length)],a={noun:t,label:`Random ${t} ${n+1}`,description:s[t]||`A random ${t}`,randomAttributes:{value:100*Math.random(),priority:Math.floor(5*Math.random())+1,tags:["tag-"+n%5,"category-"+n%3]}},o=await this.add(a.description,a);e.push(o)}const o=[],i={[ue.AttributedTo]:"Attribution relationship",[ue.Controls]:"Control relationship",[ue.Created]:"Creation relationship",[ue.Earned]:"Achievement relationship",[ue.Owns]:"Ownership relationship",[ue.MemberOf]:"Membership relationship",[ue.RelatedTo]:"General relationship",[ue.WorksWith]:"Collaboration relationship",[ue.FriendOf]:"Friendship relationship",[ue.ReportsTo]:"Reporting relationship",[ue.Supervises]:"Supervision relationship",[ue.Mentors]:"Mentorship relationship"};for(let t=0;t<n;t++){const n=Math.floor(Math.random()*e.length);let r=Math.floor(Math.random()*e.length);for(;r===n&&e.length>1;)r=Math.floor(Math.random()*e.length);const s=e[n],c=e[r],u=a[Math.floor(Math.random()*a.length)],l={verb:u,description:i[u]||`A random ${u} relationship`,weight:Math.random(),confidence:Math.random(),randomAttributes:{strength:100*Math.random(),duration:Math.floor(365*Math.random())+1,tags:["relation-"+t%5,"strength-"+t%3]}},d=await this.addVerb(s,c,void 0,{type:u,weight:l.weight,metadata:l});o.push(d)}return{nounIds:e,verbIds:o}}catch(e){throw console.error("Failed to generate random graph:",e),new Error(`Failed to generate random graph: ${e}`)}}}let xe,we;if("undefined"!=typeof process&&process.versions&&process.versions.node)try{if(xe=require("fs"),we=require("path"),!we||"function"!=typeof we.resolve)throw new Error("path module is missing required methods")}catch(e){console.warn("Failed to load Node.js modules with require:",e);try{const e=require("node:path"),t=require("node:fs");if(we=e,xe=t,!we||"function"!=typeof we.resolve)throw new Error("path module from node:path is missing required methods")}catch(e){console.warn("Failed to load Node.js modules with node: prefix:",e)}}class ve{constructor(e){this.isInitialized=!1,this.rootDir=e||"",this.nounsDir="",this.verbsDir="",this.metadataDir="",this.personDir="",this.placeDir="",this.thingDir="",this.eventDir="",this.conceptDir="",this.contentDir="",this.defaultDir=""}async init(){if(!this.isInitialized)try{if(!xe||!we||"function"!=typeof we.resolve){console.log("Node.js modules not properly loaded, attempting to load them now");const e=[async()=>{console.log("Attempting to load Node.js modules with require()");const e=require("fs"),t=require("path");if(!t||"function"!=typeof t.resolve)throw new Error("path.resolve is not a function after require()");return{fs:e,path:t}},async()=>{console.log('Attempting to load Node.js modules with require("node:...")');const e=require("node:fs"),t=require("node:path");if(!t||"function"!=typeof t.resolve)throw new Error('path.resolve is not a function after require("node:path")');return{fs:e,path:t}},async()=>{console.log("Attempting to load Node.js modules with dynamic import");const e=await Promise.resolve().then(function(){return gF}),t=await Promise.resolve().then(function(){return yF}),n=e.default||e,r=t.default||t;if(!r||"function"!=typeof r.resolve)throw new Error("path.resolve is not a function after dynamic import");return{fs:n,path:r}},async()=>{console.log('Attempting to load Node.js modules with dynamic import("node:...")');const e=await import("node:fs"),t=await import("node:path"),n=e.default||e,r=t.default||t;if(!r||"function"!=typeof r.resolve)throw new Error('path.resolve is not a function after dynamic import("node:path")');return{fs:n,path:r}}];let t=null;for(const n of e)try{const e=await n();xe=e.fs,we=e.path,console.log("Successfully loaded Node.js modules");break}catch(e){t=e,console.warn("Module loading attempt failed:",e)}if(!xe||!we||"function"!=typeof we.resolve)throw new Error(`Failed to import Node.js modules after multiple attempts: ${t}. This adapter requires a Node.js environment.`)}const e=this.rootDir||process.cwd();this.rootDir=we.resolve(e,"brainy-data"),this.nounsDir=we.join(this.rootDir,"nouns"),this.verbsDir=we.join(this.rootDir,"verbs"),this.metadataDir=we.join(this.rootDir,"metadata"),this.personDir=we.join(this.nounsDir,"person"),this.placeDir=we.join(this.nounsDir,"place"),this.thingDir=we.join(this.nounsDir,"thing"),this.eventDir=we.join(this.nounsDir,"event"),this.conceptDir=we.join(this.nounsDir,"concept"),this.contentDir=we.join(this.nounsDir,"content"),this.defaultDir=we.join(this.nounsDir,"default"),await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.personDir),await this.ensureDirectoryExists(this.placeDir),await this.ensureDirectoryExists(this.thingDir),await this.ensureDirectoryExists(this.eventDir),await this.ensureDirectoryExists(this.conceptDir),await this.ensureDirectoryExists(this.contentDir),await this.ensureDirectoryExists(this.defaultDir),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize file system storage:",e),new Error(`Failed to initialize file system storage: ${e}`)}}async saveNoun(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodeDirectory(e.id),r=we.join(n,`${e.id}.json`);await xe.promises.writeFile(r,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e),n=we.join(t,`${e}.json`);try{await xe.promises.access(n)}catch{if(t!==this.defaultDir){const n=we.join(this.defaultDir,`${e}.json`);try{await xe.promises.access(n);const e=await xe.promises.readFile(n,"utf8"),t=JSON.parse(e),r=new Map;for(const[e,n]of Object.entries(t.connections))r.set(Number(e),new Set(n));return{id:t.id,vector:t.vector,connections:r}}catch{const n=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const r of n){if(r===t)continue;const n=we.join(r,`${e}.json`);try{await xe.promises.access(n);const e=await xe.promises.readFile(n,"utf8"),t=JSON.parse(e),r=new Map;for(const[e,n]of Object.entries(t.connections))r.set(Number(e),new Set(n));return{id:t.id,vector:t.vector,connections:r}}catch{}}return null}}return null}const r=await xe.promises.readFile(n,"utf8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(t){return console.error(`Failed to get node ${e}:`,t),null}}async getNounsByNounType(e){await this.ensureInitialized();try{let t;switch(e){case"person":t=this.personDir;break;case"place":t=this.placeDir;break;case"thing":t=this.thingDir;break;case"event":t=this.eventDir;break;case"concept":t=this.conceptDir;break;case"content":t=this.contentDir;break;default:t=this.defaultDir}const n=[];try{const e=(await xe.promises.readdir(t)).filter(e=>e.endsWith(".json")).map(e=>this.readNodeFromFile(we.join(t,e))),r=await Promise.all(e);n.push(...r.filter(e=>null!==e))}catch(t){console.warn(`Could not read directory for noun type ${e}:`,t)}return n}catch(t){throw console.error(`Failed to get nodes for noun type ${e}:`,t),new Error(`Failed to get nodes for noun type ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNounsByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nodes:",e),new Error(`Failed to get all nodes: ${e}`)}}async readNodeFromFile(e){try{const t=await xe.promises.readFile(e,"utf8"),n=JSON.parse(t),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r}}catch(t){return console.error(`Failed to read node from file ${e}:`,t),null}}async deleteNoun(e){await this.ensureInitialized();try{const t=await this.getNodeDirectory(e),n=we.join(t,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{if(t!==this.defaultDir){const n=we.join(this.defaultDir,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{const n=[this.personDir,this.placeDir,this.thingDir,this.eventDir,this.conceptDir,this.contentDir];for(const r of n){if(r===t)continue;const n=we.join(r,`${e}.json`);try{return await xe.promises.access(n),void await xe.promises.unlink(n)}catch{}}return}}return}}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveVerb(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=we.join(this.verbsDir,`${e.id}.json`);await xe.promises.writeFile(n,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb(e){await this.ensureInitialized();try{const t=we.join(this.verbsDir,`${e}.json`);try{await xe.promises.access(t)}catch{return null}const n=await xe.promises.readFile(t,"utf8"),r=JSON.parse(n),a=new Map;for(const[e,t]of Object.entries(r.connections))a.set(Number(e),new Set(t));return{id:r.id,vector:r.vector,connections:a,sourceId:r.sourceId,targetId:r.targetId,type:r.type,weight:r.weight,metadata:r.metadata}}catch(t){return console.error(`Failed to get edge ${e}:`,t),null}}async getAllVerbs(){await this.ensureInitialized();try{const e=(await xe.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).map(e=>{const t=we.basename(e,".json");return this.getVerb(t)});return(await Promise.all(e)).filter(e=>null!==e)}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return(await this.getAllVerbs()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async deleteVerb(e){await this.ensureInitialized();try{const t=we.join(this.verbsDir,`${e}.json`);try{await xe.promises.access(t)}catch{return}await xe.promises.unlink(t)}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{const n=we.join(this.metadataDir,`${e}.json`);await xe.promises.writeFile(n,JSON.stringify(t,null,2),"utf8")}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=we.join(this.metadataDir,`${e}.json`);try{await xe.promises.access(t)}catch{return null}const n=await xe.promises.readFile(t,"utf8");return JSON.parse(n)}catch(t){return console.error(`Failed to get metadata for ${e}:`,t),null}}async clear(){await this.ensureInitialized();try{await this.deleteDirectory(this.nounsDir),await this.deleteDirectory(this.verbsDir),await this.deleteDirectory(this.metadataDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.personDir),await this.ensureDirectoryExists(this.placeDir),await this.ensureDirectoryExists(this.thingDir),await this.ensureDirectoryExists(this.eventDir),await this.ensureDirectoryExists(this.conceptDir),await this.ensureDirectoryExists(this.contentDir),await this.ensureDirectoryExists(this.defaultDir)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async ensureInitialized(){this.isInitialized||await this.init()}async ensureDirectoryExists(e){try{await xe.promises.access(e)}catch{await xe.promises.mkdir(e,{recursive:!0})}}async deleteDirectory(e){try{const t=await xe.promises.readdir(e);for(const n of t){const t=we.join(e,n);(await xe.promises.stat(t)).isDirectory()?await this.deleteDirectory(t):await xe.promises.unlink(t)}await xe.promises.rmdir(e)}catch(e){if("ENOENT"!==e.code)throw e}}async countFilesInDirectory(e){try{return(await xe.promises.readdir(e)).filter(e=>e.endsWith(".json")).length}catch(e){if("ENOENT"===e.code)return 0;throw e}}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}async getNodeDirectory(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return this.personDir;case"place":return this.placeDir;case"thing":return this.thingDir;case"event":return this.eventDir;case"concept":return this.conceptDir;case"content":return this.contentDir;default:return this.defaultDir}return this.defaultDir}catch(e){return this.defaultDir}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await xe.promises.readdir(e);for(const a of r){const r=we.join(e,a),s=await xe.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){console.warn(`Error calculating size for ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.personDir),o=await t(this.placeDir),i=await t(this.thingDir),c=await t(this.eventDir),u=await t(this.conceptDir),l=await t(this.contentDir),d=await t(this.defaultDir);e=n+r+a;let h=null,p={nounTypes:{person:{size:s,count:await this.countFilesInDirectory(this.personDir)},place:{size:o,count:await this.countFilesInDirectory(this.placeDir)},thing:{size:i,count:await this.countFilesInDirectory(this.thingDir)},event:{size:c,count:await this.countFilesInDirectory(this.eventDir)},concept:{size:u,count:await this.countFilesInDirectory(this.conceptDir)},content:{size:l,count:await this.countFilesInDirectory(this.contentDir)},default:{size:d,count:await this.countFilesInDirectory(this.defaultDir)}}};try{const e=await xe.promises.statfs(this.rootDir);if(e){const t=e.bavail*e.bsize,n=e.blocks*e.bsize;h=n,p={availableSpace:t,totalSpace:n,freePercentage:t/n*100}}}catch(e){console.warn("Unable to get filesystem stats:",e);try{const{exec:e}=await Promise.resolve().then(function(){return bF}),t=(await Promise.resolve().then(function(){return Vc})).promisify(e),{stdout:n}=await t(`df -k "${this.rootDir}"`),r=n.trim().split("\n");if(r.length>1){const e=r[1].split(/\s+/);if(e.length>=4){const t=parseInt(e[1],10),n=(parseInt(e[2],10),parseInt(e[3],10));h=1024*t,p={availableSpace:1024*n,totalSpace:1024*t,freePercentage:n/t*100}}}}catch(e){console.warn("Unable to get disk space using df command:",e)}}return{type:"filesystem",used:e,quota:h,details:p}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}}var ke=Object.freeze({__proto__:null,FileSystemStorage:ve});const Ie="nouns/",Se="verbs/",Ne="verbs/",Te="metadata/",Ee="nouns/person/",$e="place/",Ce="thing/",Re="event/",Ae="concept/",_e="content/",De="default/";class Oe{async saveNoun(e){return this.saveNode(e)}async getNoun(e){return this.getNode(e)}async getAllNouns(){return this.getAllNodes()}async getNounsByNounType(e){return this.getNodesByNounType(e)}async deleteNoun(e){return this.deleteNode(e)}async saveVerb(e){return this.saveEdge(e)}async getVerb(e){return this.getEdge(e)}async getAllVerbs(){return this.getAllEdges()}async getVerbsBySource(e){return this.getEdgesBySource(e)}async getVerbsByTarget(e){return this.getEdgesByTarget(e)}async getVerbsByType(e){return this.getEdgesByType(e)}async deleteVerb(e){return this.deleteEdge(e)}constructor(e){this.isInitialized=!1,this.bucketName=e.bucketName,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.serviceType=e.serviceType,this.accountId=e.accountId,this.region=e.region,this.endpoint=e.endpoint}async init(){if(!this.isInitialized)try{try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};switch(this.serviceType){case"r2":if(!this.accountId)throw new Error("accountId is required for Cloudflare R2");t.region="auto",t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`;break;case"s3":if(!this.region)throw new Error("region is required for Amazon S3");t.region=this.region;break;case"gcs":this.endpoint||(this.endpoint="https://storage.googleapis.com"),t.endpoint=this.endpoint,t.region=this.region||"auto";break;case"custom":if(!this.endpoint)throw new Error("endpoint is required for custom S3-compatible services");t.endpoint=this.endpoint,this.region&&(t.region=this.region);break;default:throw new Error(`Unsupported service type: ${this.serviceType}`)}this.s3Client=new e(t),this.isInitialized=!0}catch(e){throw new Error(`Failed to import AWS SDK: ${e}. Make sure @aws-sdk/client-s3 is installed.`)}}catch(e){throw console.error(`Failed to initialize ${this.serviceType} storage:`,e),new Error(`Failed to initialize ${this.serviceType} storage: ${e}`)}}async saveNode(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.getNodePrefix(e.id),{PutObjectCommand:r}=await import("@aws-sdk/client-s3");await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${n}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNode(e){await this.ensureInitialized();try{const t=await this.getNodePrefix(e),{GetObjectCommand:n}=await import("@aws-sdk/client-s3");try{const r=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${t}${e}.json`})),a=await r.Body.transformToString(),s=JSON.parse(a),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch(r){if(t!==De)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`})),r=await t.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch{const r=[Ee,$e,Ce,Re,Ae,_e];for(const a of r)if(a!==t)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${a}${e}.json`})),r=await t.Body.transformToString(),s=JSON.parse(r),o=new Map;for(const[e,t]of Object.entries(s.connections))o.set(Number(e),new Set(t));return{id:s.id,vector:s.vector,connections:o}}catch{}}return null}}catch(t){return console.error(`Failed to get node ${e}:`,t),null}}async getNodesByNounType(e){await this.ensureInitialized();try{let t;switch(e){case"person":t=Ee;break;case"place":t=$e;break;case"thing":t=Ce;break;case"event":t=Re;break;case"concept":t=Ae;break;case"content":t=_e;break;default:t=De}const{ListObjectsV2Command:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3"),a=await this.s3Client.send(new n({Bucket:this.bucketName,Prefix:`${Ie}${t}`})),s=[];if(!a.Contents||0===a.Contents.length)return s;const o=a.Contents.map(async e=>{try{const t=await this.s3Client.send(new r({Bucket:this.bucketName,Key:e.Key})),n=await t.Body.transformToString(),a=JSON.parse(n),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(t){return console.error(`Failed to get node from ${e.Key}:`,t),null}});return(await Promise.all(o)).filter(e=>null!==e)}catch(t){throw console.error(`Failed to get nodes for noun type ${e}:`,t),new Error(`Failed to get nodes for noun type ${e}: ${t}`)}}async getAllNodes(){await this.ensureInitialized();try{const e=["person","place","thing","event","concept","content","default"].map(e=>this.getNodesByNounType(e)),t=await Promise.all(e),n=[];for(const e of t)n.push(...e);return n}catch(e){throw console.error("Failed to get all nodes:",e),new Error(`Failed to get all nodes: ${e}`)}}async deleteNode(e){await this.ensureInitialized();try{const t=await this.getNodePrefix(e),{DeleteObjectCommand:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3");try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${t}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${t}${e}.json`}))}catch{if(t!==De)try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${De}${e}.json`}))}catch{const a=[Ee,$e,Ce,Re,Ae,_e];for(const s of a)if(s!==t)try{return await this.s3Client.send(new r({Bucket:this.bucketName,Key:`${Ie}${s}${e}.json`})),void await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ie}${s}${e}.json`}))}catch{}}return}}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Se}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getEdge(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Se}${e}.json`})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch{return null}}catch(t){return console.error(`Failed to get edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:Se})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata}}catch(t){return console.error(`Failed to get edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){throw console.error("Failed to get all edges:",e),new Error(`Failed to get all edges: ${e}`)}}async getEdgesBySource(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.sourceId===e)}catch(t){throw console.error(`Failed to get edges by source ${e}:`,t),new Error(`Failed to get edges by source ${e}: ${t}`)}}async getEdgesByTarget(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.targetId===e)}catch(t){throw console.error(`Failed to get edges by target ${e}:`,t),new Error(`Failed to get edges by target ${e}: ${t}`)}}async getEdgesByType(e){await this.ensureInitialized();try{return(await this.getAllEdges()).filter(t=>t.type===e)}catch(t){throw console.error(`Failed to get edges by type ${e}:`,t),new Error(`Failed to get edges by type ${e}: ${t}`)}}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t,GetObjectCommand:n}=await import("@aws-sdk/client-s3");try{await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Ne}${e}.json`})),await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Ne}${e}.json`}))}catch{return}}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{const{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${Te}${e}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"}))}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");try{const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${Te}${e}.json`})),r=await n.Body.transformToString();return JSON.parse(r)}catch{return null}}catch(t){return console.error(`Failed to get metadata for ${e}:`,t),null}}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName}));if(!n.Contents||0===n.Contents.length)return;const r=n.Contents.map(async e=>{try{await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))}catch(t){console.error(`Failed to delete object ${e.Key}:`,t)}});await Promise.all(r)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async getStorageStatus(){await this.ensureInitialized();try{const{ListObjectsV2Command:e}=await import("@aws-sdk/client-s3"),t=await this.s3Client.send(new e({Bucket:this.bucketName}));let n=0,r=0,a=0,s=0;if(t.Contents)for(const e of t.Contents){n+=e.Size||0;const t=e.Key||"";t.startsWith(Ie)?r++:t.startsWith(Se)?a++:t.startsWith(Te)&&s++}const o={person:0,place:0,thing:0,event:0,concept:0,content:0,default:0},i=[{type:"person",prefix:Ee},{type:"place",prefix:$e},{type:"thing",prefix:Ce},{type:"event",prefix:Re},{type:"concept",prefix:Ae},{type:"content",prefix:_e},{type:"default",prefix:De}];for(const{type:t,prefix:n}of i){const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:`${Ie}${n}`}));o[t]=r.Contents?.length||0}return{type:this.serviceType,used:n,quota:null,details:{nodeCount:r,edgeCount:a,metadataCount:s,nounTypes:{person:{count:o.person},place:{count:o.place},thing:{count:o.thing},event:{count:o.event},concept:{count:o.concept},content:{count:o.content},default:{count:o.default}}}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}async ensureInitialized(){this.isInitialized||await this.init()}async getNodePrefix(e){try{const t=await this.getMetadata(e);if(t&&t.noun)switch(t.noun){case"person":return Ee;case"place":return $e;case"thing":return Ce;case"event":return Re;case"concept":return Ae;case"content":return _e;default:return De}return De}catch(e){return De}}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}var Fe=Object.freeze({__proto__:null,R2Storage:Oe,S3CompatibleStorage:Oe});let Me=null;const Pe=[];function Be(e){return void 0===e.enabled&&(e.enabled=!0),Pe.push(e),e}function Le(e){const t=e||Me;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Pe)e.enabled&&t.register(e);return t}function ze(e,t){const n=Pe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function We(e){return Pe.filter(t=>{switch(e){case le.SENSE:return"processRawData"in t&&"listenToFeed"in t;case le.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case le.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case le.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case le.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case le.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case le.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case le.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class Ve{constructor(e){this.enabled=!0,this.isInitialized=!1,this.name=e.name,this.description=e.description||`${e.name} augmentation`,this.enabled=!1!==e.enabled}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}function Ue(e){const t=new Ve(e);return t.processRawData=async(n,r)=>{if(await t.ensureInitialized(),e.processRawData){const t=e.processRawData(n,r);return t instanceof Promise?await t:t}return{success:!1,data:{nouns:[],verbs:[]},error:"processRawData not implemented"}},t.listenToFeed=async(n,r)=>{if(await t.ensureInitialized(),e.listenToFeed)return e.listenToFeed(n,r);throw new Error("listenToFeed not implemented")},e.autoRegister&&(Be(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function Ge(e,t){const n=e;return n.connectWebSocket=async(n,r)=>{if(await(e.ensureInitialized?.()),t.connectWebSocket)return t.connectWebSocket(n,r);throw new Error("connectWebSocket not implemented")},n.sendWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.sendWebSocketMessage)return t.sendWebSocketMessage(n,r);throw new Error("sendWebSocketMessage not implemented")},n.onWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.onWebSocketMessage)return t.onWebSocketMessage(n,r);throw new Error("onWebSocketMessage not implemented")},n.offWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.offWebSocketMessage)return t.offWebSocketMessage(n,r);throw new Error("offWebSocketMessage not implemented")},n.closeWebSocket=async(n,r,a)=>{if(await(e.ensureInitialized?.()),t.closeWebSocket)return t.closeWebSocket(n,r,a);throw new Error("closeWebSocket not implemented")},n}async function He(e,t,...n){try{if(!e.enabled)return{success:!1,data:null,error:`Augmentation ${e.name} is disabled`};if("function"!=typeof e[t])return{success:!1,data:null,error:`Method ${t} not found on augmentation ${e.name}`};return await e[t](...n)}catch(n){return console.error(`Error executing ${t} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}}async function je(e,t={}){try{const n=await e,r=[];for(const e in n){const a=n[e];a&&"object"==typeof a&&("string"==typeof a.name&&"function"==typeof a.initialize&&"function"==typeof a.shutDown&&"function"==typeof a.getStatus&&(r.push(a),t.autoRegister&&(Be(a),t.autoInitialize&&a.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${a.name}:`,e)}))))}return r}catch(e){return console.error("Error loading augmentation module:",e),[]}}var qe;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(qe||(qe={}));const Ke={mode:qe.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class Xe{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case le.SENSE:return[...this.registry.sense];case le.CONDUIT:return[...this.registry.conduit];case le.COGNITION:return[...this.registry.cognition];case le.MEMORY:return[...this.registry.memory];case le.PERCEPTION:return[...this.registry.perception];case le.DIALOG:return[...this.registry.dialog];case le.ACTIVATION:return[...this.registry.activation];case le.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(le.SENSE),this.registry.conduit.length>0&&e.push(le.CONDUIT),this.registry.cognition.length>0&&e.push(le.COGNITION),this.registry.memory.length>0&&e.push(le.MEMORY),this.registry.perception.length>0&&e.push(le.PERCEPTION),this.registry.dialog.length>0&&e.push(le.DIALOG),this.registry.activation.length>0&&e.push(le.ACTIVATION),this.registry.webSocket.length>0&&e.push(le.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===qe.THREADED)&&C())}async execute(e,t,n=[],r={}){const a={...Ke,...r},s=e.filter(e=>!1!==e.enabled);if(0===s.length)return{results:[],errors:[],successful:[]};const o={results:[],errors:[],successful:[]},i=async e=>{try{if(a.timeout){const r=new Promise((n,r)=>{setTimeout(()=>{r(new Error(`Timeout executing ${t} on ${e.name}`))},a.timeout)});let s;if(this.shouldUseThreading(a))try{s=A(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return await Promise.race([s,r])}return await He(e,t,...n)}catch(e){return o.errors.push(e instanceof Error?e:new Error(String(e))),{success:!1,data:null,error:e instanceof Error?e.message:String(e)}}};switch(a.mode){case qe.PARALLEL:case qe.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case qe.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case qe.FIRST_RESULT:for(const e of s){const t=await i(e);if(o.results.push(t),t.success&&null!==t.data&&void 0!==t.data)break}break;case qe.SEQUENTIAL:default:for(const e of s){const t=await i(e);if(o.results.push(t),a.stopOnError&&!t.success)break}}return o.successful=o.results.filter(e=>e.success),o}async executeByType(e,t,n=[],r={}){const a=this.getAugmentationsByType(e);return this.execute(a,t,n,r)}async executeSingle(e,t,...n){return He(e,t,...n)}async processStaticData(e,t,n={}){let r,a=e;for(const e of t){const t=e.transformArgs?e.transformArgs(a,r):[a],n=await this.executeSingle(e.augmentation,e.method,...t);if(!n.success)return n;a=n.data,r=n}return r}async processStreamingData(e,t,n,r,a,s={}){const o=async e=>{let t,n=e;for(const e of r){const r=e.transformArgs?e.transformArgs(n,t):[n],s=await this.executeSingle(e.augmentation,e.method,...r);if(!s.success)return void a(s);n=s.data,t=s}a(t)};await this.executeSingle(e,t,...n,e=>{o(e).catch(e=>{console.error("Error processing streaming data:",e),a({success:!1,data:null,error:e instanceof Error?e.message:String(e)})})})}createPipeline(e,t={}){return n=>this.processStaticData(n,e,t)}createStreamingPipeline(e,t,n,r={}){return(a,s)=>this.processStreamingData(e,t,a,n,s,r)}async executeSensePipeline(e,t,n={}){return(await this.executeByType(le.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(le.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(le.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(le.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(le.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(le.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(le.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const Ye=new Xe;!function(e){Me=e}(Ye);const Qe=Ye,Je=(e,t,n=[],r={})=>Ye.execute(e,t,n,r),Ze=(e,t,n=[],r={})=>Ye.executeByType(e,t,n,r),et=(e,t,...n)=>Ye.executeSingle(e,t,...n),tt=(e,t,n={})=>Ye.processStaticData(e,t,n),nt=(e,t,n,r,a,s={})=>Ye.processStreamingData(e,t,n,r,a,s),rt=(e,t={})=>Ye.createPipeline(e,t),at=(e,t,n,r={})=>Ye.createStreamingPipeline(e,t,n,r),st=qe;var ot;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(ot||(ot={}));const it={mode:ot.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const ct=new class{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}async executeSensePipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...it,...n};return this.executeTypedPipeline(this.registry.activation,e,t,r)}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case le.SENSE:return[...this.registry.sense];case le.CONDUIT:return[...this.registry.conduit];case le.COGNITION:return[...this.registry.cognition];case le.MEMORY:return[...this.registry.memory];case le.PERCEPTION:return[...this.registry.perception];case le.DIALOG:return[...this.registry.dialog];case le.ACTIVATION:return[...this.registry.activation];case le.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(le.SENSE),this.registry.conduit.length>0&&e.push(le.CONDUIT),this.registry.cognition.length>0&&e.push(le.COGNITION),this.registry.memory.length>0&&e.push(le.MEMORY),this.registry.perception.length>0&&e.push(le.PERCEPTION),this.registry.dialog.length>0&&e.push(le.DIALOG),this.registry.activation.length>0&&e.push(le.ACTIVATION),this.registry.webSocket.length>0&&e.push(le.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===ot.THREADED)&&C())}async executeTypedPipeline(e,t,n,r){const a=e.filter(e=>!1!==e.enabled);if(0===a.length)return[];const s=async e=>{try{const a=r.timeout?new Promise((n,a)=>{setTimeout(()=>{a(new Error(`Timeout executing ${String(t)} on ${e.name}`))},r.timeout)}):null;let s;if(this.shouldUseThreading(r))try{s=A(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return a?await Promise.race([s,a]):await s}catch(n){return console.error(`Error executing ${String(t)} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}};switch(r.mode){case ot.PARALLEL:return a.map(s);case ot.THREADED:const e={...r,forceThreading:!0},t=async t=>{const n=r;r=e;const a=await s(t);return r=n,a};return a.map(t);case ot.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case ot.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case ot.SEQUENTIAL:default:const n=[];for(const e of a){const t=s(e);if(n.push(t),r.stopOnError){if(!(await t).success)break}}return n}}};let ut,lt,dt;const ht=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(ut=globalThis.TransformStream,lt=globalThis.ReadableStream,dt=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{ut=e.TransformStream,lt=e.ReadableStream,dt=e.WritableStream}).catch(e=>{throw console.error("Failed to import WebStreams API:",e),new Error("WebStreams API is not available in this environment. Please use a modern browser or Node.js 18+.")}),pt={timeout:3e4,stopOnError:!1};class ft{constructor(e={}){this.brainyData=e.brainyData||new be}async ensureStreamClassesInitialized(){await ht}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...pt,...n},a={success:!0,data:null,stageResults:{}};try{const n=await ct.executeSensePipeline("processRawData",[e,t],{timeout:r.timeout,stopOnError:r.stopOnError});let s=null;for(const e of n){const t=await e;if(t.success){s=t;break}}if(!s||!s.success)return{success:!1,data:null,error:"Failed to process raw data with ISense augmentations",stageResults:{sense:s||{success:!1,data:null,error:"No sense augmentations available"}}};a.stageResults.sense=s;const o=ct.getAugmentationsByType(le.MEMORY);if(0===o.length)return{success:!1,data:null,error:"No memory augmentations available",stageResults:a.stageResults};const i=o[0],c=`data_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,u=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!u.success)return{success:!1,data:null,error:`Failed to store data: ${u.error}`,stageResults:{...a.stageResults,memory:u}};a.stageResults.memory=u;const l=await ct.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of l){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await ct.executeConduitPipeline("writeData",[{dataKey:c,nouns:s.data.nouns,verbs:s.data.verbs}],{timeout:r.timeout,stopOnError:r.stopOnError});let p=null;for(const e of h){const t=await e;if(t.success){p=t;break}}p&&(a.stageResults.conduit=p);const f=await ct.executeActivationPipeline("triggerAction",["dataProcessed",{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let m=null;for(const e of f){const t=await e;if(t.success){m=t;break}}m&&(a.stageResults.activation=m);const g=await ct.executePerceptionPipeline("interpret",[s.data.nouns,s.data.verbs,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let y=null;for(const e of g){const t=await e;if(t.success){y=t;break}}return y?(a.stageResults.perception=y,a.data=y.data):a.data=d?d.data:{dataKey:c},a}catch(e){return{success:!1,data:null,error:`Pipeline execution failed: ${e}`,stageResults:a.stageResults}}}async createWebSocketHandler(e,t,n={}){await this.ensureStreamClassesInitialized();const r=new ut({transform:async(e,r)=>{try{const a="string"==typeof e?e:JSON.stringify(e),s=await this.processData(a,t,n);s.success?r.enqueue(s):console.warn("Pipeline processing failed:",s.error)}catch(e){console.error("Error in transform stream:",e)}}}),a=new dt({write:async t=>{if(e.send&&"function"==typeof e.send)try{await e.send(JSON.stringify(t))}catch(e){console.error("Error sending result back to WebSocket:",e)}}});return r.readable.pipeTo(a).catch(e=>{console.error("Error in pipeline stream:",e)}),e=>{try{const t=r.writable.getWriter();t.write(e).catch(e=>{console.error("Error writing to stream:",e)}).finally(()=>{t.releaseLock()})}catch(e){console.error("Error getting writer for transform stream:",e)}}}async setupWebSocketPipeline(e,t,n={}){await this.ensureStreamClassesInitialized();const r=ct.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new lt({start:e=>{const t=t=>{try{const n="string"==typeof t.data?t.data:t.data instanceof Blob?new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.readAsText(t.data)}):JSON.stringify(t.data);n instanceof Promise?n.then(t=>{e.enqueue(t)}).catch(e=>{console.error("Error processing blob data:",e)}):e.enqueue(n)}catch(e){console.error("Error processing WebSocket message:",e)}},n=e=>{t({data:e})};s._streamMessageHandler=t,s._messageHandlerWrapper=n,a.onWebSocketMessage(s.connectionId,n).catch(t=>{console.error("Error registering WebSocket message handler:",t),e.error(t)})},cancel:()=>{s._messageHandlerWrapper&&(a.offWebSocketMessage(s.connectionId,s._messageHandlerWrapper).catch(e=>{console.error("Error removing WebSocket message handler:",e)}),delete s._streamMessageHandler,delete s._messageHandlerWrapper)}}),i=this.createWebSocketHandler(s,t,n),c=new dt({write:async e=>{if(!s.send||"function"!=typeof s.send)throw new Error("WebSocket connection does not support sending data");try{const t="string"==typeof e?e:JSON.stringify(e);await s.send(t)}catch(e){throw console.error("Error sending data to WebSocket:",e),e}},close:()=>{s.close&&"function"==typeof s.close&&s.close().catch(e=>{console.error("Error closing WebSocket connection:",e)})}});o.pipeThrough(new ut({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new dt({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const u=s;return u.readableStream=o,u.writableStream=c,u}}const mt=new ft,gt={autoInitialize:!1,debug:!1};async function yt(e,t={}){const n={...gt,...t},r={augmentations:[],errors:[]};n.debug&&console.log(`[AugmentationRegistryLoader] Loading augmentations from ${Object.keys(e).length} modules`);for(const[t,a]of Object.entries(e))try{n.debug&&console.log(`[AugmentationRegistryLoader] Processing module: ${t}`);const e=bt(a);if(0===e.length){n.debug&&console.log(`[AugmentationRegistryLoader] No augmentations found in module: ${t}`);continue}for(const t of e)try{const e=Be(t);r.augmentations.push(e),n.debug&&console.log(`[AugmentationRegistryLoader] Registered augmentation: ${e.name}`)}catch(e){const t=e instanceof Error?e:new Error(String(e));r.errors.push(t),n.debug&&console.error(`[AugmentationRegistryLoader] Failed to register augmentation: ${t.message}`)}}catch(e){const a=e instanceof Error?e:new Error(String(e));r.errors.push(a),n.debug&&console.error(`[AugmentationRegistryLoader] Error processing module ${t}: ${a.message}`)}return n.debug&&console.log(`[AugmentationRegistryLoader] Loaded ${r.augmentations.length} augmentations with ${r.errors.length} errors`),r}function bt(e){const t=[];if(xt(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(xt(r)&&t.push(r),Array.isArray(r)&&r.every(xt)&&t.push(...r))}return t}function xt(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function wt(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function vt(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class kt{constructor(e,t){this.description="Base memory augmentation",this.enabled=!0,this.isInitialized=!1,this.name=e,this.storage=t}async initialize(){if(!this.isInitialized)try{await this.storage.init(),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async storeData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to store data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to store data: ${t}`}}}async retrieveData(e,t){await this.ensureInitialized();try{return{success:!0,data:await this.storage.getMetadata(e)}}catch(t){return console.error(`Failed to retrieve data for key ${e}:`,t),{success:!1,data:null,error:`Failed to retrieve data: ${t}`}}}async updateData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to update data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to update data: ${t}`}}}async deleteData(e,t){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,null),{success:!0,data:!0}}catch(t){return console.error(`Failed to delete data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to delete data: ${t}`}}}async listDataKeys(e,t){return{success:!1,data:[],error:"listDataKeys is not supported by this storage adapter"}}async search(e,t=10,n){await this.ensureInitialized();try{let n;if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))return{success:!1,data:[],error:"Query must be a vector (array of numbers) for vector search"};n=e;const r=await this.storage.getAllNouns(),a=[];for(const e of r){if(!e.vector||!Array.isArray(e.vector))continue;const t=await this.storage.getMetadata(e.id),r=1-I(n,e.vector);a.push({id:e.id,score:r,data:t})}a.sort((e,t)=>t.score-e.score);return{success:!0,data:a.slice(0,t)}}catch(e){return console.error("Failed to search in storage:",e),{success:!1,data:[],error:`Failed to search in storage: ${e}`}}}async ensureInitialized(){this.isInitialized||await this.initialize()}}class It extends kt{constructor(e){super(e,new oe),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return le.MEMORY}}class St extends kt{constructor(e,t){super(e,new ve(t)),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return le.MEMORY}}class Nt extends kt{constructor(e){super(e,new se),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return le.MEMORY}}async function Tt(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new It(e);case"filesystem":return new St(e,t.rootDirectory);case"opfs":return new Nt(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new St(e,t.rootDirectory);{const n=new se;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new Nt(e)):new It(e)}}const Et="1.0.0";var $t;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}($t||($t={}));class Ct{constructor(e){this.brainyData=e}async handleRequest(e){try{switch(e.operation){case"get":return await this.handleGetRequest(e);case"search":return await this.handleSearchRequest(e);case"add":return await this.handleAddRequest(e);case"getRelationships":return await this.handleGetRelationshipsRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_OPERATION",`Operation ${e.operation} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleGetRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await this.brainyData.get(t);return n?this.createSuccessResponse(e.requestId,n):this.createErrorResponse(e.requestId,"NOT_FOUND",`No noun found with id ${t}`)}async handleSearchRequest(e){const{query:t,k:n=10}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "query" is required');const r=await this.brainyData.searchText(t,n);return this.createSuccessResponse(e.requestId,r)}async handleAddRequest(e){const{text:t,metadata:n}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "text" is required');const r=await this.brainyData.add(t,n);return this.createSuccessResponse(e.requestId,{id:r})}async handleGetRelationshipsRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await(this.brainyData.getVerbsBySource?.(t))||[],r=await(this.brainyData.getVerbsByTarget?.(t))||[];return this.createSuccessResponse(e.requestId,{outgoing:n,incoming:r})}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}}class Rt{constructor(){}async handleRequest(e){try{const{toolName:t,parameters:n}=e,r=t.split("_");if(r.length<3||"brainy"!==r[0])return this.createErrorResponse(e.requestId,"INVALID_TOOL",`Invalid tool name: ${t}. Tool names should be in the format: brainy_{augmentationType}_{method}`);const a=r[1],s=r.slice(2).join("_");if(!this.isValidAugmentationType(a))return this.createErrorResponse(e.requestId,"INVALID_AUGMENTATION_TYPE",`Invalid augmentation type: ${a}`);const o=await this.executePipeline(a,s,n);return this.createSuccessResponse(e.requestId,o)}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async getAvailableTools(){const e=[],t=ct.getAvailableAugmentationTypes();for(const n of t){const t=ct.getAugmentationsByType(n);for(const r of t){const t=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(e=>!e.startsWith("_")&&"constructor"!==e&&"initialize"!==e&&"shutDown"!==e&&"getStatus"!==e&&"function"==typeof r[e]);for(const a of t)e.push(this.createToolDefinition(n,r.name,a))}}return e}createToolDefinition(e,t,n){return{name:`brainy_${e}_${n}`,description:`Access to Brainy's ${e} augmentation '${t}' method '${n}'`,parameters:{type:"object",properties:{args:{type:"array",description:`Arguments for the ${n} method`},options:{type:"object",description:"Optional execution options"}},required:["args"]}}}async executePipeline(e,t,n){const{args:r=[],options:a={}}=n;switch(e){case le.SENSE:return await ct.executeSensePipeline(t,r,a);case le.CONDUIT:return await ct.executeConduitPipeline(t,r,a);case le.COGNITION:return await ct.executeCognitionPipeline(t,r,a);case le.MEMORY:return await ct.executeMemoryPipeline(t,r,a);case le.PERCEPTION:return await ct.executePerceptionPipeline(t,r,a);case le.DIALOG:return await ct.executeDialogPipeline(t,r,a);case le.ACTIVATION:return await ct.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(le).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}}class At{constructor(e,t={}){this.dataAdapter=new Ct(e),this.toolset=new Rt,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case $t.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case $t.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case $t.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case $t.AUTHENTICATION:return await this.handleAuthenticationRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_REQUEST_TYPE",`Request type ${e.type} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleSystemInfoRequest(e){try{switch(e.infoType){case"status":return this.createSuccessResponse(e.requestId,{status:"active",version:Et,environment:E()?"browser":$()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:Et});default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_INFO_TYPE",`Info type ${e.infoType} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleAuthenticationRequest(e){try{if(!this.options.enableAuth)return this.createSuccessResponse(e.requestId,{authenticated:!0,message:"Authentication is not enabled"});const{credentials:t}=e;if(t.apiKey&&this.options.apiKeys?.includes(t.apiKey)){const t=this.generateAuthToken("api-user");return this.createSuccessResponse(e.requestId,{authenticated:!0,token:t})}if("admin"===t.username&&"password"===t.password){const n=this.generateAuthToken(t.username);return this.createSuccessResponse(e.requestId,{authenticated:!0,token:n})}return this.createErrorResponse(e.requestId,"INVALID_CREDENTIALS","Invalid credentials")}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}isValidRequest(e){return e&&"object"==typeof e&&e.type&&e.requestId&&e.version}isAuthenticated(e){return!this.options.enableAuth||!!e.authToken&&this.isValidToken(e.authToken)}isValidToken(e){const t=this.authTokens.get(e);return!!t&&(!(t.expires<Date.now())||(this.authTokens.delete(e),!1))}generateAuthToken(e){const t=v(),n=Date.now()+864e5;return this.authTokens.set(t,{userId:e,expires:n}),t}checkRateLimit(e){if(!this.options.rateLimit)return!0;const t=Date.now(),n=this.rateLimits.get(e);return n?n.resetTime<t?(n.count=1,n.resetTime=t+this.options.rateLimit.windowMs,!0):!(n.count>=this.options.rateLimit.maxRequests)&&(n.count++,!0):(this.rateLimits.set(e,{count:1,resetTime:t+this.options.rateLimit.windowMs}),!0)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Et,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Et,error:{code:t,message:n,details:r}}}generateRequestId(){return v()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=s.Buffer);const _t={isBrowser:"undefined"!=typeof window,isNode:"undefined"!=typeof process&&process.versions&&process.versions.node,isServerless:!("undefined"!=typeof window||"undefined"!=typeof process&&process.versions&&process.versions.node)};"undefined"!=typeof globalThis&&(globalThis.__ENV__=_t),console.log(`Brainy running in ${_t.isBrowser?"browser":_t.isNode?"Node.js":"serverless/unknown"} environment`);class Dt{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class Ot{refCount(e){return Ft("refCount")}incRef(e){return Ft("incRef")}timerAvailable(){return!0}time(e){return Ft("time")}read(e){return Ft("read")}readSync(e){return Ft("readSync")}readToGPU(e,t){return Ft("readToGPU")}numDataIds(){return Ft("numDataIds")}disposeData(e,t){return Ft("disposeData")}write(e,t,n){return Ft("write")}move(e,t,n,r,a){return Ft("move")}createTensorFromGPUData(e,t,n){return Ft("createTensorFromGPUData")}memory(){return Ft("memory")}floatPrecision(){return Ft("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Ft("dispose")}}function Ft(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
10
10
  /**
11
11
  * @license
12
12
  * Copyright 2020 Google LLC. All Rights Reserved.