@soulcraft/brainy 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@ function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArr
6
6
  * @author Feross Aboukhadijeh <https://feross.org>
7
7
  * @license MIT
8
8
  */
9
- function(e){const t=s,n=f,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 o(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 u(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|m(e,t);let r=o(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=o(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)?o(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 l(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 u(e){return l(e),o(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=o(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 m(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 H(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:H(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 N(this,t,n);case"ascii":return $(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return T(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 l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(l(e,s)===l(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(l(e,s+r)!==l(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(H(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 T(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function N(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 l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(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=m,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?N(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),l=this.slice(r,a),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],o=u[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 O(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 F(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 D(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){O(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){O(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||O(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||O(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||O(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||O(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||O(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 F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return D(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);O(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);O(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||O(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||O(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||O(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||O(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||O(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 F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return D(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 j=/[^+/0-9A-Za-z-_]/g;function H(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(j,"")).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")}}(a);let I=!1;if("undefined"!=typeof globalThis&&g())try{void 0===globalThis.TextEncoder&&(globalThis.TextEncoder=TextEncoder),void 0===globalThis.TextDecoder&&(globalThis.TextDecoder=TextDecoder),"undefined"!=typeof global&&(global.TextEncoder||(global.TextEncoder=TextEncoder),global.TextDecoder||(global.TextDecoder=TextDecoder),global.__TextEncoder__=TextEncoder,global.__TextDecoder__=TextDecoder);const e={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}};if("undefined"!=typeof global&&(global.__brainy_util__=e),"undefined"!=typeof global&&global.require&&global.require.cache)for(const t in global.require.cache)if(t.endsWith("/util.js")||"util"===t){const n=global.require.cache[t];n&&n.exports&&Object.assign(n.exports,e)}try{const e=require("util");e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}if("undefined"!=typeof global){const e=global.Float32Array;global.Float32Array=class extends e{constructor(e,t,n){if(e instanceof ArrayBuffer){const r=t||0,a=void 0!==n?n:(e.byteLength-r)/4;if((e.byteLength-r)%4!=0&&void 0===n){const t=4*Math.floor((e.byteLength-r)/4),n=new ArrayBuffer(t),a=new Uint8Array(e,r,t);new Uint8Array(n).set(a),super(n)}else super(e,r,a)}else super(e,t,n)}},Object.setPrototypeOf(global.Float32Array,e),Object.defineProperty(global.Float32Array,"name",{value:"Float32Array"}),Object.defineProperty(global.Float32Array,"BYTES_PER_ELEMENT",{value:4})}if("undefined"!=typeof global){const e=e=>{e&&"object"==typeof e&&!e.TextEncoder&&(e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder,e.types=e.types||{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray})};global._utilShim&&e(global._utilShim),"undefined"!=typeof globalThis&&globalThis._utilShim&&e(globalThis._utilShim),global._utilShim?e(global._utilShim):global._utilShim={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}},"undefined"==typeof globalThis||globalThis._utilShim||(globalThis._utilShim=global._utilShim);try{Object.defineProperty(global,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}try{Object.defineProperty(globalThis,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}}console.log("Brainy: Successfully patched TensorFlow.js PlatformNode at module load time"),I=!0}catch(e){console.warn("Brainy: Failed to apply early TensorFlow.js platform patch:",e)}async function S(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};if(!I||void 0===e.__TextEncoder__||void 0===e.__TextDecoder__)try{console.log("Brainy: Applying TensorFlow.js platform patch via function call"),e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder),e.__TextEncoder__=TextEncoder,e.__TextDecoder__=TextDecoder,"undefined"!=typeof process&&process.versions&&(process.versions.node||(process.versions.node=process.version));try{const e=await Promise.resolve().then(function(){return Ft});e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}I=!0}catch(e){console.warn("Brainy: Failed to apply TensorFlow.js platform patch:",e)}}S().catch(e=>{console.warn("Failed to apply TensorFlow patch at module load:",e)});var T=Object.freeze({__proto__:null,applyTensorFlowPatch:S});const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;let E;N&&(N.TextEncoder||(N.TextEncoder=TextEncoder),N.TextDecoder||(N.TextDecoder=TextDecoder),N.__TextEncoder__=TextEncoder,N.__TextDecoder__=TextDecoder),S(),console.log("Applied TensorFlow.js patch via ES modules in setup.ts");const $=new Uint8Array(16);function C(){if(!E&&(E="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!E))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return E($)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));var A={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _(e,t,n){if(A.randomUUID&&!e)return A.randomUUID();const r=(e=e||{}).random||(e.rng||C)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]}(r)}const O=(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)},F=(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))},D=(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)},M=(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 P(e,t,n=O){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))}}const B=new Map;function L(e,t){if(g())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 l;if(B.size<4)l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Add isFloat32Array and isTypedArray directly to util\n isFloat32Array: (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr &&\n Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n },\n isTypedArray: (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n },\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\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}}),B.set(c,l);else{const n=Array.from(B.keys()),r=n[Math.floor(Math.random()*n.length)];l=B.get(r),l._busy&&(l.terminate(),l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\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}}),B.set(r,l)),l._busy=!0}l.on("message",e=>{l._busy=!1,n(e.result)}),l.on("error",e=>{l._busy=!1,r(e)}),l.on("exit",e=>{0!==e&&(l._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(m()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{let a,s="./worker.js";try{if(void 0!==import.meta&&import.meta.url){s=`${import.meta.url.substring(0,import.meta.url.lastIndexOf("/")+1)}worker.js`}else if("undefined"!=typeof document){const e=document.getElementsByTagName("script");for(let t=0;t<e.length;t++){const n=e[t].src;if(n&&n.includes("unified.js")){s=n.substring(0,n.lastIndexOf("/")+1)+"worker.js";break}}}}catch(e){console.warn("Could not determine worker path from import.meta.url, using relative path",e)}if("./worker.js"===s&&"undefined"!=typeof window){const e=window.location.href,t=e.substring(0,e.lastIndexOf("/")+1);if(s=`${t}worker.js`,"undefined"!=typeof document){const e=`${t}dist/worker.js`,n=new XMLHttpRequest;n.open("HEAD",e,!1);try{n.send(),n.status>=200&&n.status<300&&(s=e)}catch(e){}}}console.log("Using worker path:",s);try{a=new Worker(s)}catch(s){console.warn("Failed to create Web Worker from file, trying inline worker:",s);try{const e=new Blob(["\n // Brainy Inline Worker Script\n console.log('Brainy Inline Worker: Started');\n\n self.onmessage = function (e) {\n try {\n console.log('Brainy Inline Worker: Received message', e.data ? 'with data' : 'without data');\n\n if (!e.data || !e.data.fnString) {\n throw new Error('Invalid message: missing function string');\n }\n\n console.log('Brainy Inline Worker: Creating function from string');\n const fn = new Function('return ' + e.data.fnString)();\n\n console.log('Brainy Inline Worker: Executing function with args');\n const result = fn(e.data.args);\n\n console.log('Brainy Inline Worker: Function executed successfully, posting result');\n self.postMessage({ result: result });\n } catch (error) {\n console.error('Brainy Inline Worker: Error executing function', error);\n self.postMessage({ \n error: error.message,\n stack: error.stack\n });\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);a=new Worker(t),console.log("Created inline worker using Blob URL")}catch(a){console.warn("Failed to create inline Web Worker, falling back to main thread execution:",a);try{const r=new Function("return "+e)();return void n(r(t))}catch(e){return void r(e)}}}const o=setTimeout(()=>{console.warn("Web Worker execution timed out, falling back to main thread"),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},25e3);a.onmessage=function(e){clearTimeout(o),e.data.error?r(new Error(e.data.error)):n(e.data.result),a.terminate()},a.onerror=function(s){clearTimeout(o),console.warn("Web Worker error, falling back to main thread execution:",s.message),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},a.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{let n;try{n=new Function("return "+e)()}catch(t){console.warn("Fallback: Error creating function with return syntax, trying alternative approaches",t);try{n=new Function("return ("+e+")")()}catch(r){console.warn("Fallback: Error creating function with parentheses wrapping",r);try{n=new Function(e)()}catch(r){console.warn("Fallback: Direct approach failed, trying with function wrapper",r);try{n=new Function("return function(args) { return ("+e+")(args); }")()}catch(e){throw console.error("Fallback: All approaches to create function failed",e),new Error("Failed to create function from string: "+t.message)}}}}return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function z(){g()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of B.values())e.terminate();B.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let W=class{constructor(e={}){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu",this.verbose=!0,this.verbose=void 0===e.verbose||e.verbose}addServerCompatibilityPolyfills(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};try{e.util||(e.util={}),e.util.isFloat32Array||(e.util.isFloat32Array=e=>!!(e instanceof Float32Array||e&&"[object Float32Array]"===Object.prototype.toString.call(e))),e.util.isTypedArray||(e.util.isTypedArray=e=>!(!ArrayBuffer.isView(e)||e instanceof DataView))}catch(e){console.warn("Failed to add utility polyfills:",e)}}isTestEnvironment(){return"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))}logger(e,t,...n){("error"===e||this.verbose)&&console[e](t,...n)}async loadModelWithRetry(e,t=3,n=1e3){let r=null;for(let a=0;a<=t;a++)try{this.logger("log",0===a?"Loading Universal Sentence Encoder model...":`Retrying Universal Sentence Encoder model loading (attempt ${a+1}/${t+1})...`);const n=await e();return a>0&&this.logger("log","Universal Sentence Encoder model loaded successfully after retry"),n}catch(e){r=e;const s=r.message||String(r),o=s.includes("Failed to parse model JSON")||s.includes("Failed to fetch")||s.includes("Network error")||s.includes("ENOTFOUND")||s.includes("ECONNRESET")||s.includes("ETIMEDOUT")||s.includes("JSON")||s.includes("model.json");if(!(a<t&&o))throw a>=t?this.logger("error",`Universal Sentence Encoder model loading failed after ${t+1} attempts. Last error: ${s}`):this.logger("error",`Universal Sentence Encoder model loading failed with non-retryable error: ${s}`),r;{const e=n*Math.pow(2,a);this.logger("warn",`Universal Sentence Encoder model loading failed (attempt ${a+1}): ${s}. Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e))}}throw r||new Error("Unknown error during model loading")}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.addServerCompatibilityPolyfills();try{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;if(e)try{if("undefined"!=typeof process&&process.versions&&process.versions.node){const t=await Promise.resolve().then(function(){return Ft});e.TextEncoder||(e.TextEncoder=t.TextEncoder),e.TextDecoder||(e.TextDecoder=t.TextDecoder)}}catch(t){e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder)}const{applyTensorFlowPatch:t}=await Promise.resolve().then(function(){return T});await t(),this.tf=await Promise.resolve().then(function(){return ky}),await Promise.resolve().then(function(){return aS});try{if("undefined"!=typeof window){await Promise.resolve().then(function(){return MO});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.use=await Promise.resolve().then(function(){return gD})}catch(e){throw this.logger("error","Failed to initialize TensorFlow.js:",e),e}this.tf.setBackend&&await this.tf.setBackend(this.backend);const t=function(e){let t=null;if(e.load&&"function"==typeof e.load)t=e.load;else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load;else if(e.default&&"function"==typeof e.default)t=e.default;else if("function"==typeof e)t=e;else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load;else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.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];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];break}}if(t)break}return t}(this.use);if(!t)throw new Error("Could not find Universal Sentence Encoder load function");this.model=await this.loadModelWithRetry(t),this.initialized=!0,console.warn=e}catch(e){throw this.logger("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 this.logger("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 this.logger("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){this.logger("error","Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function V(e,t,n=[],r=!0){"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))||console[e](t,...n)}function U(e){return e?async t=>await e.embed(t):q()}let G=null,j=!1,H=!0;function q(e={}){return void 0!==e.verbose&&(H=e.verbose),G||(G=new W({verbose:H})),async e=>{try{if(!j)try{await G.init(),j=!0}catch(e){throw j=!1,e}return await G.embed(e)}catch(e){throw V("error","Failed to use TensorFlow embedding:",[e],H),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}function K(e={}){return q(e)}const X=K();let Y=null,Q=!1,J=!0;function Z(e={}){return void 0!==e.verbose&&(J=e.verbose),Y||(Y=new W({verbose:J})),async e=>{try{return Q||(await Y.init(),Q=!0),await Y.embedBatch(e)}catch(e){throw V("error","Failed to use TensorFlow batch embedding:",[e],J),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}}}function ee(e={}){return Z(e)}const te=ee();function ne(e){const t=U(e);return async e=>{const n=t.toString();return await L(n,e)}}var re=Object.freeze({__proto__:null,UniversalSentenceEncoder:W,createBatchEmbeddingFunction:Z,createEmbeddingFunction:U,createTensorFlowEmbeddingFunction:q,createThreadedEmbeddingFunction:ne,defaultBatchEmbeddingFunction:te,defaultEmbeddingFunction:X,getDefaultBatchEmbeddingFunction:ee,getDefaultEmbeddingFunction:K});const ae={M:16,efConstruction:200,efSearch:50,ml:16};class se{constructor(e={},t=O,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...ae,...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 P(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 l=this.nouns.get(t);if(!l){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const u=l.connections.get(r)||new Set;if(this.useParallelization&&u.size>=10){const t=[];for(const e of u)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 u)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 oe={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class ie{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 ce extends se{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={...oe,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new ie(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 ie(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 le="nouns",ue="verbs",de="metadata",he="index";class pe{constructor(){this.isInitialized=!1}async ensureInitialized(){this.isInitialized||await this.init()}async saveNoun(e){return await this.ensureInitialized(),this.saveNode(e)}async getNoun(e){return await this.ensureInitialized(),this.getNode(e)}async getAllNouns(){return await this.ensureInitialized(),this.getAllNodes()}async getNounsByNounType(e){return await this.ensureInitialized(),this.getNodesByNounType(e)}async deleteNoun(e){return await this.ensureInitialized(),this.deleteNode(e)}async saveVerb(e){return await this.ensureInitialized(),this.saveEdge(e)}async getVerb(e){return await this.ensureInitialized(),this.getEdge(e)}async getAllVerbs(){return await this.ensureInitialized(),this.getAllEdges()}async getVerbsBySource(e){return await this.ensureInitialized(),this.getEdgesBySource(e)}async getVerbsByTarget(e){return await this.ensureInitialized(),this.getEdgesByTarget(e)}async getVerbsByType(e){return await this.ensureInitialized(),this.getEdgesByType(e)}async deleteVerb(e){return await this.ensureInitialized(),this.deleteEdge(e)}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}class fe extends pe{constructor(){super(),this.nouns=new Map,this.verbs=new Map,this.metadata=new Map}async init(){this.isInitialized=!0}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));this.nouns.set(e.id,t)}async getNode(e){const t=this.nouns.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllNodes(){const e=[];for(const[t,n]of this.nouns.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getNodesByNounType(e){const t=[];for(const[n,r]of this.nouns.entries()){const a=await this.getMetadata(n);if(a&&a.noun===e){const e={id:r.id,vector:[...r.vector],connections:new Map};for(const[t,n]of r.connections.entries())e.connections.set(t,new Set(n));t.push(e)}}return t}async deleteNode(e){this.nouns.delete(e)}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};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};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllEdges(){const e=[];for(const[t,n]of this.verbs.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){this.verbs.delete(e)}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 clear(){this.nouns.clear(),this.verbs.clear(),this.metadata.clear()}async getStorageStatus(){return{type:"memory",used:0,quota:null,details:{nodeCount:this.nouns.size,edgeCount:this.verbs.size,metadataCount:this.metadata.size}}}}async function me(e){return e.getFile()}class ge extends pe{constructor(){super(),this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.indexDir=null,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(le,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(ue,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(de,{create:!0}),this.indexDir=await this.rootDir.getDirectoryHandle(he,{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 saveNode(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.nounsDir.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 node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNode(e){await this.ensureInitialized();try{const t=await this.nounsDir.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(e){return null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.nounsDir.entries())if("file"===n.kind)try{const t=await me(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}catch(e){console.error(`Error reading node file ${t}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{for await(const[n,r]of this.nounsDir.entries())if("file"===r.kind)try{const n=await me(r),a=await n.text(),s=JSON.parse(a),o=await this.getMetadata(s.id);if(o&&o.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}catch(e){console.error(`Error reading node file ${n}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return t}async deleteNode(e){await this.ensureInitialized();try{await this.nounsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting node ${e}:`,t),t}}async saveEdge(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 edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getEdge(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(e){return null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.verbsDir.entries())if("file"===n.kind)try{const t=await me(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}catch(e){console.error(`Error reading edge file ${t}:`,e)}}catch(e){console.error("Error reading verbs directory:",e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting edge ${e}:`,t),t}}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 ${e}:`,t),new Error(`Failed to save metadata ${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(e){return null}}async clear(){await this.ensureInitialized();const e=async e=>{try{for await(const[t,n]of e.entries())await e.removeEntry(t)}catch(e){throw console.error("Error removing directory contents:",e),e}};try{await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}catch(e){throw console.error("Error clearing storage:",e),e}}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)),this.indexDir&&(e+=await t(this.indexDir));let r=null,a={isPersistent:await this.isPersistent(),nounTypes:{}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();r=e.quota||null,a={...a,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)}this.nounsDir&&(a.nounsCount=await n(this.nounsDir)),this.verbsDir&&(a.verbsCount=await n(this.verbsDir)),this.metadataDir&&(a.metadataCount=await n(this.metadataDir));const s={};if(this.metadataDir)for await(const[e,t]of this.metadataDir.entries())if("file"===t.kind)try{const e=await me(t),n=await e.text(),r=JSON.parse(n);r.noun&&(s[r.noun]=(s[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return a.nounTypes=s,{type:"opfs",used:e,quota:r,details:a}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}}let ye,be;try{const e=import("fs"),t=import("path");Promise.all([e,t]).then(([e,t])=>{ye=e,be=t.default}).catch(e=>{console.error("Failed to load Node.js modules:",e)})}catch(e){console.error("FileSystemStorage: Failed to load Node.js modules. This adapter is not supported in this environment.",e)}class xe extends pe{constructor(e){super(),this.rootDir=e,this.nounsDir=be.join(this.rootDir,le),this.verbsDir=be.join(this.rootDir,ue),this.metadataDir=be.join(this.rootDir,de),this.indexDir=be.join(this.rootDir,he)}async init(){if(!this.isInitialized){if(!ye||!be)throw new Error("FileSystemStorage requires a Node.js environment, but `fs` and `path` modules could not be loaded.");try{await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.indexDir),this.isInitialized=!0}catch(e){throw console.error("Error initializing FileSystemStorage:",e),e}}}async ensureDirectoryExists(e){try{await ye.promises.mkdir(e,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}async saveNode(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=be.join(this.nounsDir,`${e.id}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getNode(e){await this.ensureInitialized();const t=be.join(this.nounsDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8"),n=JSON.parse(e),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"ENOENT"!==t.code&&console.error(`Error reading node ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{const t=await ye.promises.readdir(this.nounsDir);for(const n of t)if(n.endsWith(".json")){const t=be.join(this.nounsDir,n),r=await ye.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{const n=await ye.promises.readdir(this.nounsDir);for(const r of n)if(r.endsWith(".json")){const n=be.join(this.nounsDir,r),a=await ye.promises.readFile(n,"utf-8"),s=JSON.parse(a),o=s.id,i=await this.getMetadata(o);if(i&&i.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return t}async deleteNode(e){await this.ensureInitialized();const t=be.join(this.nounsDir,`${e}.json`);try{await ye.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting node file ${t}:`,e),e}}async saveEdge(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=be.join(this.verbsDir,`${e.id}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getEdge(e){await this.ensureInitialized();const t=be.join(this.verbsDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8"),n=JSON.parse(e),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,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{const t=await ye.promises.readdir(this.verbsDir);for(const n of t)if(n.endsWith(".json")){const t=be.join(this.verbsDir,n),r=await ye.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.verbsDir}:`,e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();const t=be.join(this.verbsDir,`${e}.json`);try{await ye.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting edge file ${t}:`,e),e}}async saveMetadata(e,t){await this.ensureInitialized();const n=be.join(this.metadataDir,`${e}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getMetadata(e){await this.ensureInitialized();const t=be.join(this.metadataDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8");return JSON.parse(e)}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading metadata ${e}:`,t),null}}async clear(){await this.ensureInitialized();const e=async t=>{try{const n=await ye.promises.readdir(t);for(const r of n){const n=be.join(t,r);(await ye.promises.stat(n)).isDirectory()?(await e(n),await ye.promises.rmdir(n)):await ye.promises.unlink(n)}}catch(e){if("ENOENT"!==e.code)throw console.error(`Error removing directory contents ${t}:`,e),e}};await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await ye.promises.readdir(e);for(const a of r){const r=be.join(e,a),s=await ye.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){"ENOENT"!==t.code&&console.error(`Error calculating size for directory ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.indexDir);e=n+r+a+s;const o=(await ye.promises.readdir(this.nounsDir)).filter(e=>e.endsWith(".json")).length,i=(await ye.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).length,c=(await ye.promises.readdir(this.metadataDir)).filter(e=>e.endsWith(".json")).length,l={},u=await ye.promises.readdir(this.metadataDir);for(const e of u)if(e.endsWith(".json"))try{const t=be.join(this.metadataDir,e),n=await ye.promises.readFile(t,"utf-8"),r=JSON.parse(n);r.noun&&(l[r.noun]=(l[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return{type:"filesystem",used:e,quota:null,details:{rootDirectory:this.rootDir,nounsCount:o,verbsCount:i,metadataCount:c,nounsDirSize:n,verbsDirSize:r,metadataDirSize:a,indexDirSize:s,nounTypes:l}}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}}class we extends pe{constructor(e){super(),this.s3Client=null,this.bucketName=e.bucketName,this.region=e.region||"auto",this.endpoint=e.endpoint,this.accountId=e.accountId,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken,this.serviceType=e.serviceType||"s3",this.nounPrefix=`${le}/`,this.verbPrefix=`${ue}/`,this.metadataPrefix=`${de}/`,this.indexPrefix=`${he}/`}async init(){if(!this.isInitialized)try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={region:this.region,credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};this.sessionToken&&(t.credentials.sessionToken=this.sessionToken),this.endpoint&&(t.endpoint=this.endpoint),"r2"===this.serviceType&&this.accountId&&(t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`),this.s3Client=new e(t);const{HeadBucketCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName})),this.isInitialized=!0}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{console.log(`Saving node ${e.id} to bucket ${this.bucketName}`);const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.nounPrefix}${e.id}.json`,a=JSON.stringify(t,null,2);console.log(`Saving node to key: ${r}`),console.log(`Node data: ${a.substring(0,100)}${a.length>100?"...":""}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Node ${e.id} saved successfully:`,s);const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));t&&t.Body?console.log(`Verified node ${e.id} was saved correctly`):console.error(`Failed to verify node ${e.id} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify node ${e.id} was saved correctly:`,t)}}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{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting node ${e} from bucket ${this.bucketName}`);const n=`${this.nounPrefix}${e}.json`;console.log(`Looking for node at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No node found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed node data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections))return console.error(`Invalid node data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n};return console.log(`Successfully retrieved node ${e}:`,r),r}catch(t){return console.error(`Failed to parse node data for ${e}:`,t),null}}catch(t){return console.log(`Error getting node for ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting all nodes from bucket ${this.bucketName} with prefix ${this.nounPrefix}`);const n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.nounPrefix})),r=[];if(!n||!n.Contents||0===n.Contents.length)return console.log(`No nodes found in bucket ${this.bucketName} with prefix ${this.nounPrefix}`),r;console.log(`Found ${n.Contents.length} nodes in bucket ${this.bucketName}`),console.log("Keys found:");for(const e of n.Contents)e&&e.Key&&console.log(`- ${e.Key}`);const a=n.Contents.map(async e=>{if(!e||!e.Key)return console.log("Skipping undefined object or object without Key"),null;try{const n=e.Key.replace(this.nounPrefix,"").replace(".json","");console.log(`Getting node with ID ${n} from key ${e.Key}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}));if(!r||!r.Body)return console.log(`No response or response body for node ${n}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body for ${n}: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const e=JSON.parse(a);if(console.log(`Parsed node data for ${n}:`,e),!(e&&e.id&&e.vector&&e.connections))return console.error(`Invalid node data for ${n}:`,e),null;const t=new Map;for(const[n,r]of Object.entries(e.connections))t.set(Number(n),new Set(r));const r={id:e.id,vector:e.vector,connections:t};return console.log(`Successfully retrieved node ${n}:`,r),r}catch(e){return console.error(`Failed to parse node data for ${n}:`,e),null}}catch(t){return console.error(`Error getting node from ${e.Key}:`,t),null}}),s=(await Promise.all(a)).filter(e=>null!==e);console.log(`Returning ${s.length} nodes`);for(const e of s)console.log(`- Node ${e.id}`);return s}catch(e){return console.error("Failed to get all nodes:",e),[]}}async getNodesByNounType(e){await this.ensureInitialized();try{const t=await this.getAllNodes(),n=[];for(const r of t){const t=await this.getMetadata(r.id);t&&t.noun===e&&n.push(r)}return n}catch(t){return console.error(`Failed to get nodes by noun type ${e}:`,t),[]}}async deleteNode(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.nounPrefix}${e}.json`}))}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:`${this.verbPrefix}${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");console.log(`Getting edge ${e} from bucket ${this.bucketName}`);const n=`${this.verbPrefix}${e}.json`;console.log(`Looking for edge at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No edge found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved edge body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed edge data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections&&t.sourceId&&t.targetId&&t.type))return console.error(`Invalid edge data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n,sourceId:t.sourceId,targetId:t.targetId,type:t.type,weight:t.weight||1,metadata:t.metadata||{}};return console.log(`Successfully retrieved edge ${e}:`,r),r}catch(t){return console.error(`Failed to parse edge data for ${e}:`,t),null}}catch(t){return console.log(`Error getting edge for ${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:this.verbPrefix})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{e.Key.replace(this.verbPrefix,"").replace(".json","");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(`Error getting edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){return console.error("Failed to get all edges:",e),[]}}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.verbPrefix}${e}.json`}))}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{console.log(`Saving metadata for ${e} to bucket ${this.bucketName}`);const{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.metadataPrefix}${e}.json`,a=JSON.stringify(t,null,2);console.log(`Saving metadata to key: ${r}`),console.log(`Metadata: ${a}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Metadata for ${e} saved successfully:`,s);const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));if(t&&t.Body){const n=await t.Body.transformToString();console.log(`Verified metadata for ${e} was saved correctly: ${n}`)}else console.error(`Failed to verify metadata for ${e} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify metadata for ${e} was saved correctly:`,t)}}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");console.log(`Getting metadata for ${e} from bucket ${this.bucketName}`);const n=`${this.metadataPrefix}${e}.json`;console.log(`Looking for metadata at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No metadata found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved metadata body: ${a}`);try{const t=JSON.parse(a);return console.log(`Successfully retrieved metadata for ${e}:`,t),t}catch(t){return console.error(`Failed to parse metadata for ${e}:`,t),null}}catch(t){if("NoSuchKey"===t.name||t.message&&(t.message.includes("NoSuchKey")||t.message.includes("not found")||t.message.includes("does not exist")))return console.log(`Metadata not found for ${e}`),null;throw console.error(`Error getting metadata for ${e}:`,t),t}}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=async n=>{const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:n}));if(r&&r.Contents&&0!==r.Contents.length)for(const e of r.Contents)e&&e.Key&&await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))};await n(this.nounPrefix),await n(this.verbPrefix),await n(this.metadataPrefix),await n(this.indexPrefix)}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");let t=0,n=0,r=0,a=0;const s=async t=>{let n=0,r=0;const a=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:t}));if(!a||!a.Contents||0===a.Contents.length)return{size:n,count:r};for(const e of a.Contents)if(e){n+=("number"==typeof e.Size?e.Size:e.Size?parseInt(e.Size.toString(),10):0)||0,r++,0===n&&r>0&&(n=100*r)}return{size:n,count:r}},o=await s(this.nounPrefix),i=await s(this.verbPrefix),c=await s(this.metadataPrefix),l=await s(this.indexPrefix);t=o.size+i.size+c.size+l.size,n=o.count,r=i.count,a=c.count,0===t&&(n>0||r>0||a>0)&&(console.log(`Setting minimum size for ${n} nodes, ${r} edges, and ${a} metadata objects`),t=100*(n+r+a)),(n>0||r>0||a>0)&&(console.log(`Ensuring positive size for storage status with ${n} nodes, ${r} edges, and ${a} metadata objects`),t=Math.max(t,1));const u={},d=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.metadataPrefix}));if(d&&d.Contents){const{GetObjectCommand:e}=await import("@aws-sdk/client-s3");for(const t of d.Contents)if(t&&t.Key)try{const n=await this.s3Client.send(new e({Bucket:this.bucketName,Key:t.Key}));if(n&&n.Body){const e=await n.Body.transformToString();try{const t=JSON.parse(e);t&&t.noun&&(u[t.noun]=(u[t.noun]||0)+1)}catch(e){console.error(`Failed to parse metadata from ${t.Key}:`,e)}}}catch(e){console.error(`Error getting metadata from ${t.Key}:`,e)}}return{type:this.serviceType,used:t,quota:null,details:{bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,nodeCount:n,edgeCount:r,metadataCount:a,nounTypes:u}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}}async function ve(e={}){if(e.forceMemoryStorage)return console.log("Using memory storage (forced)"),new fe;if(e.forceFileSystemStorage)return console.log("Using file system storage (forced)"),new xe(e.rootDirectory||"./brainy-data");if(e.type&&"auto"!==e.type)switch(e.type){case"memory":return console.log("Using memory storage"),new fe;case"opfs":{const t=new ge;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}return console.warn("OPFS storage is not available, falling back to memory storage"),new fe}case"filesystem":return console.log("Using file system storage"),new xe(e.rootDirectory||"./brainy-data");case"s3":return e.s3Storage?(console.log("Using Amazon S3 storage"),new we({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"})):(console.warn("S3 storage configuration is missing, falling back to memory storage"),new fe);case"r2":return e.r2Storage?(console.log("Using Cloudflare R2 storage"),new we({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"})):(console.warn("R2 storage configuration is missing, falling back to memory storage"),new fe);case"gcs":return e.gcsStorage?(console.log("Using Google Cloud Storage"),new we({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"})):(console.warn("GCS storage configuration is missing, falling back to memory storage"),new fe);default:return console.warn(`Unknown storage type: ${e.type}, falling back to memory storage`),new fe}if(e.customS3Storage)return console.log(`Using custom S3-compatible storage: ${e.customS3Storage.serviceType||"custom"}`),new we({bucketName:e.customS3Storage.bucketName,region:e.customS3Storage.region,endpoint:e.customS3Storage.endpoint,accessKeyId:e.customS3Storage.accessKeyId,secretAccessKey:e.customS3Storage.secretAccessKey,serviceType:e.customS3Storage.serviceType||"custom"});if(e.r2Storage)return console.log("Using Cloudflare R2 storage"),new we({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"});if(e.s3Storage)return console.log("Using Amazon S3 storage"),new we({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"});if(e.gcsStorage)return console.log("Using Google Cloud Storage"),new we({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"});const t=new ge;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage (auto-detected)"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}try{if("undefined"!=typeof process&&process.versions&&process.versions.node)return console.log("Using file system storage (auto-detected)"),new xe(e.rootDirectory||"./brainy-data")}catch(e){}return console.log("Using memory storage (auto-detected)"),new fe}const ke={Person:"person",Place:"place",Thing:"thing",Event:"event",Concept:"concept",Content:"content",Group:"group",List:"list",Category:"category"},Ie={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 Se;!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"}(Se||(Se={}));class Te{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 Ne extends Te{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 Se.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:_(),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:_(),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=_(),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 Ee extends Te{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 Se.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=_();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=_();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:_(),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:_(),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=_(),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 $e(e,t,n={}){switch(e){case"websocket":const n=new Ne(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new Ee(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class Ce extends Ne{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 Re{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 Se.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 Ae(e,t={}){const n=new Ce(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new Re(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 _e{get dimensions(){return this._dimensions}get maxConnections(){return this.index.getConfig().M||16}get efConstruction(){return this.index.getConfig().efConstruction||200}constructor(e={}){if(this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.loggingConfig={verbose:!0},this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,void 0!==e.dimensions&&e.dimensions<=0)throw new Error("Dimensions must be a positive number");this._dimensions=e.dimensions||512,this.distanceFunction=e.distanceFunction||F,e.hnswOptimized?(this.index=new ce(e.hnswOptimized,this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0):this.index=new se(e.hnsw,this.distanceFunction),this.storage=e.storageAdapter||null,void 0!==e.logging&&(this.loggingConfig={...this.loggingConfig,...e.logging}),e.embeddingFunction?this.embeddingFunction=e.embeddingFunction:this.embeddingFunction=K({verbose:this.loggingConfig?.verbose}),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{await this.embeddingFunction("")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e);try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return re}),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){let e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};if(e.s3Storage)if(e.s3Storage.bucketName&&e.s3Storage.accessKeyId&&e.s3Storage.secretAccessKey);else{const{s3Storage:t,...n}=e;e=n,console.warn("Ignoring s3Storage configuration due to missing required fields")}this.storage=await ve(e)}await this.storage.init(),this.useOptimizedIndex&&this.index instanceof ce&&this.index.setStorage(this.storage);const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)t.vector.length===this._dimensions?await this.index.addItem({id:t.id,vector:t.vector}):console.warn(`Skipping noun ${t.id} due to dimension mismatch: expected ${this._dimensions}, got ${t.vector.length}`);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 Ae(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");if(r.length!==this._dimensions)throw new Error(`Vector dimension mismatch: expected ${this._dimensions}, got ${r.length}`);const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:_());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(ke).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ke.Concept)}let e=t;t&&"object"==typeof t&&(e={...t,id:a}),await this.storage.saveMetadata(a,e)}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 addItem(e,t,n={}){return this.add(e,t,{...n,forceEmbed:!0})}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 te(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const l=await Promise.all([...i,...c]);r.push(...l)}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={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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;let r=await this.storage.getMetadata(e);null===r&&(r={}),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;let a=await this.storage.getMetadata(t);null===a&&(a={}),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(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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(ke).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ke.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{let a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a&&r.autoCreateMissingNouns)try{const t=new Array(this._dimensions).fill(0),n=r.missingNounMetadata||{autoCreated:!0,createdAt:(new Date).toISOString(),noun:ke.Concept};await this.add(t,n,{id:e}),a=this.index.getNouns().get(e),console.warn(`Auto-created missing source noun with ID ${e}`)}catch(t){throw console.error(`Failed to auto-create source noun with ID ${e}:`,t),new Error(`Failed to auto-create source noun with ID ${e}: ${t}`)}if(!s&&r.autoCreateMissingNouns)try{const e=new Array(this._dimensions).fill(0),n=r.missingNounMetadata||{autoCreated:!0,createdAt:(new Date).toISOString(),noun:ke.Concept};await this.add(e,n,{id:t}),s=this.index.getNouns().get(t),console.warn(`Auto-created missing target noun with ID ${t}`)}catch(e){throw console.error(`Failed to auto-create target noun with ID ${t}:`,e),new Error(`Failed to auto-create target noun with ID ${t}: ${e}`)}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||_();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(Ie).includes(c)||(console.warn(`Invalid verb type: ${c}. Using RelatedTo as default.`),c=Ie.RelatedTo)}const l={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 u=this.index.getNouns().get(o);if(!u)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);return l.connections=u.connections,await this.storage.saveVerb(l),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 ce){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(),z(),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(ke),r=Object.values(Ie),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||Ie.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 se(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(ke),a=e.verbTypes||Object.values(Ie);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[ke.Person]:"A person with unique characteristics",[ke.Place]:"A location with specific attributes",[ke.Thing]:"An object with distinct properties",[ke.Event]:"An occurrence with temporal aspects",[ke.Concept]:"An abstract idea or notion",[ke.Content]:"A piece of content or information",[ke.Group]:"A collection of related entities",[ke.List]:"An ordered sequence of items",[ke.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={[Ie.AttributedTo]:"Attribution relationship",[Ie.Controls]:"Control relationship",[Ie.Created]:"Creation relationship",[Ie.Earned]:"Achievement relationship",[Ie.Owns]:"Ownership relationship",[Ie.MemberOf]:"Membership relationship",[Ie.RelatedTo]:"General relationship",[Ie.WorksWith]:"Collaboration relationship",[Ie.FriendOf]:"Friendship relationship",[Ie.ReportsTo]:"Reporting relationship",[Ie.Supervises]:"Supervision relationship",[Ie.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],l=a[Math.floor(Math.random()*a.length)],u={verb:l,description:i[l]||`A random ${l} 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:l,weight:u.weight,metadata:u});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 Oe=null;const Fe=[];function De(e){return void 0===e.enabled&&(e.enabled=!0),Fe.push(e),e}function Me(e){const t=e||Oe;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Fe)e.enabled&&t.register(e);return t}function Pe(e,t){const n=Fe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function Be(e){return Fe.filter(t=>{switch(e){case Se.SENSE:return"processRawData"in t&&"listenToFeed"in t;case Se.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case Se.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case Se.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case Se.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case Se.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case Se.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case Se.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class Le{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 ze(e){const t=new Le(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&&(De(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function We(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 Ve(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 Ue(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&&(De(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 Ge;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(Ge||(Ge={}));const je={mode:Ge.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class He{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 Se.SENSE:return[...this.registry.sense];case Se.CONDUIT:return[...this.registry.conduit];case Se.COGNITION:return[...this.registry.cognition];case Se.MEMORY:return[...this.registry.memory];case Se.PERCEPTION:return[...this.registry.perception];case Se.DIALOG:return[...this.registry.dialog];case Se.ACTIVATION:return[...this.registry.activation];case Se.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Se.SENSE),this.registry.conduit.length>0&&e.push(Se.CONDUIT),this.registry.cognition.length>0&&e.push(Se.COGNITION),this.registry.memory.length>0&&e.push(Se.MEMORY),this.registry.perception.length>0&&e.push(Se.PERCEPTION),this.registry.dialog.length>0&&e.push(Se.DIALOG),this.registry.activation.length>0&&e.push(Se.ACTIVATION),this.registry.webSocket.length>0&&e.push(Se.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===Ge.THREADED)&&v())}async execute(e,t,n=[],r={}){const a={...je,...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=L(((...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 Ve(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 Ge.PARALLEL:case Ge.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case Ge.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case Ge.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 Ge.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 Ve(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(Se.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(Se.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(Se.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(Se.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(Se.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(Se.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(Se.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const qe=new He;!function(e){Oe=e}(qe);const Ke=qe,Xe=(e,t,n=[],r={})=>qe.execute(e,t,n,r),Ye=(e,t,n=[],r={})=>qe.executeByType(e,t,n,r),Qe=(e,t,...n)=>qe.executeSingle(e,t,...n),Je=(e,t,n={})=>qe.processStaticData(e,t,n),Ze=(e,t,n,r,a,s={})=>qe.processStreamingData(e,t,n,r,a,s),et=(e,t={})=>qe.createPipeline(e,t),tt=(e,t,n,r={})=>qe.createStreamingPipeline(e,t,n,r),nt=Ge;var rt;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(rt||(rt={}));const at={mode:rt.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const st=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={...at,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...at,...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 Se.SENSE:return[...this.registry.sense];case Se.CONDUIT:return[...this.registry.conduit];case Se.COGNITION:return[...this.registry.cognition];case Se.MEMORY:return[...this.registry.memory];case Se.PERCEPTION:return[...this.registry.perception];case Se.DIALOG:return[...this.registry.dialog];case Se.ACTIVATION:return[...this.registry.activation];case Se.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Se.SENSE),this.registry.conduit.length>0&&e.push(Se.CONDUIT),this.registry.cognition.length>0&&e.push(Se.COGNITION),this.registry.memory.length>0&&e.push(Se.MEMORY),this.registry.perception.length>0&&e.push(Se.PERCEPTION),this.registry.dialog.length>0&&e.push(Se.DIALOG),this.registry.activation.length>0&&e.push(Se.ACTIVATION),this.registry.webSocket.length>0&&e.push(Se.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===rt.THREADED)&&v())}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=L(((...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 rt.PARALLEL:return a.map(s);case rt.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 rt.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case rt.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case rt.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 ot,it,ct;const lt=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(ot=globalThis.TransformStream,it=globalThis.ReadableStream,ct=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{ot=e.TransformStream,it=e.ReadableStream,ct=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+.")}),ut={timeout:3e4,stopOnError:!1};class dt{constructor(e={}){this.brainyData=e.brainyData||new _e}async ensureStreamClassesInitialized(){await lt}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...ut,...n},a={success:!0,data:null,stageResults:{}};try{const n=await st.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=st.getAugmentationsByType(Se.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)}`,l=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!l.success)return{success:!1,data:null,error:`Failed to store data: ${l.error}`,stageResults:{...a.stageResults,memory:l}};a.stageResults.memory=l;const u=await st.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of u){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await st.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 st.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 st.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 ot({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 ct({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=st.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new it({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 ct({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 ot({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new ct({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const l=s;return l.readableStream=o,l.writableStream=c,l}}const ht=new dt,pt={autoInitialize:!1,debug:!1};async function ft(e,t={}){const n={...pt,...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=mt(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=De(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 mt(e){const t=[];if(gt(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(gt(r)&&t.push(r),Array.isArray(r)&&r.every(gt)&&t.push(...r))}return t}function gt(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function yt(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function bt(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class xt{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-F(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 wt extends xt{constructor(e){super(e,new fe),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return Se.MEMORY}}class vt extends xt{constructor(e,t){super(e,new xe(t||".")),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return Se.MEMORY}}class kt extends xt{constructor(e){super(e,new ge),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return Se.MEMORY}}async function It(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new wt(e);case"filesystem":return new vt(e,t.rootDirectory);case"opfs":return new kt(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new vt(e,t.rootDirectory);{const n=new ge;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new kt(e)):new wt(e)}}const St="1.0.0";var Tt;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}(Tt||(Tt={}));class Nt{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:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class Et{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=st.getAvailableAugmentationTypes();for(const n of t){const t=st.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 Se.SENSE:return await st.executeSensePipeline(t,r,a);case Se.CONDUIT:return await st.executeConduitPipeline(t,r,a);case Se.COGNITION:return await st.executeCognitionPipeline(t,r,a);case Se.MEMORY:return await st.executeMemoryPipeline(t,r,a);case Se.PERCEPTION:return await st.executePerceptionPipeline(t,r,a);case Se.DIALOG:return await st.executeDialogPipeline(t,r,a);case Se.ACTIVATION:return await st.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(Se).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class $t{constructor(e,t={}){this.dataAdapter=new Nt(e),this.toolset=new Et,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case Tt.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case Tt.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case Tt.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case Tt.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:St,environment:m()?"browser":g()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:St});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=_(),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:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=a.Buffer);const Ct={get isBrowser(){return m()},get isNode(){return g()},get isServerless(){return!m()&&!g()}};"undefined"!=typeof globalThis&&(globalThis.__ENV__=Ct),console.log(`Brainy running in ${Ct.isBrowser?"browser":Ct.isNode?"Node.js":"serverless/unknown"} environment`);const Rt=globalThis.TextEncoder||"undefined"!=typeof global&&global.TextEncoder||class{encode(e){return new Uint8Array(Buffer.from(e,"utf8"))}},At=globalThis.TextDecoder||"undefined"!=typeof global&&global.TextDecoder||class{decode(e){return Buffer.from(e).toString("utf8")}},_t={isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray};var Ot={TextEncoder:Rt,TextDecoder:At,types:_t};var Ft=Object.freeze({__proto__:null,TextDecoder:At,TextEncoder:Rt,default:Ot,promises:{},types:_t});
9
+ function(e){const t=s,n=f,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 o(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 u(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|m(e,t);let r=o(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=o(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)?o(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 l(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 u(e){return l(e),o(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=o(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 m(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 H(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:H(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 N(this,t,n);case"ascii":return $(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return T(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 l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(l(e,s)===l(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(l(e,s+r)!==l(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(H(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 T(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function N(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 l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(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=m,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?N(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),l=this.slice(r,a),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],o=u[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 O(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 F(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 D(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){O(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){O(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||O(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||O(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||O(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||O(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||O(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 F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return D(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);O(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);O(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||O(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||O(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||O(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||O(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||O(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 F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return D(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 j=/[^+/0-9A-Za-z-_]/g;function H(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(j,"")).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")}}(a);let I=!1;if("undefined"!=typeof globalThis&&g())try{void 0===globalThis.TextEncoder&&(globalThis.TextEncoder=TextEncoder),void 0===globalThis.TextDecoder&&(globalThis.TextDecoder=TextDecoder),"undefined"!=typeof global&&(global.TextEncoder||(global.TextEncoder=TextEncoder),global.TextDecoder||(global.TextDecoder=TextDecoder),global.__TextEncoder__=TextEncoder,global.__TextDecoder__=TextDecoder);const e={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}};if("undefined"!=typeof global&&(global.__brainy_util__=e),"undefined"!=typeof global&&global.require&&global.require.cache)for(const t in global.require.cache)if(t.endsWith("/util.js")||"util"===t){const n=global.require.cache[t];n&&n.exports&&Object.assign(n.exports,e)}try{const e=require("util");e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}if("undefined"!=typeof global){const e=global.Float32Array;global.Float32Array=class extends e{constructor(e,t,n){if(e instanceof ArrayBuffer){const r=t||0,a=void 0!==n?n:(e.byteLength-r)/4;if((e.byteLength-r)%4!=0&&void 0===n){const t=4*Math.floor((e.byteLength-r)/4),n=new ArrayBuffer(t),a=new Uint8Array(e,r,t);new Uint8Array(n).set(a),super(n)}else super(e,r,a)}else super(e,t,n)}},Object.setPrototypeOf(global.Float32Array,e),Object.defineProperty(global.Float32Array,"name",{value:"Float32Array"}),Object.defineProperty(global.Float32Array,"BYTES_PER_ELEMENT",{value:4})}if("undefined"!=typeof global){const e=e=>{e&&"object"==typeof e&&!e.TextEncoder&&(e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder,e.types=e.types||{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray})};global._utilShim&&e(global._utilShim),"undefined"!=typeof globalThis&&globalThis._utilShim&&e(globalThis._utilShim),global._utilShim?e(global._utilShim):global._utilShim={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}},"undefined"==typeof globalThis||globalThis._utilShim||(globalThis._utilShim=global._utilShim);try{Object.defineProperty(global,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}try{Object.defineProperty(globalThis,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}}console.log("Brainy: Successfully patched TensorFlow.js PlatformNode at module load time"),I=!0}catch(e){console.warn("Brainy: Failed to apply early TensorFlow.js platform patch:",e)}async function S(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};if(!I||void 0===e.__TextEncoder__||void 0===e.__TextDecoder__)try{console.log("Brainy: Applying TensorFlow.js platform patch via function call"),e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder),e.__TextEncoder__=TextEncoder,e.__TextDecoder__=TextDecoder,"undefined"!=typeof process&&process.versions&&(process.versions.node||(process.versions.node=process.version));try{const e=await Promise.resolve().then(function(){return Ft});e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}I=!0}catch(e){console.warn("Brainy: Failed to apply TensorFlow.js platform patch:",e)}}S().catch(e=>{console.warn("Failed to apply TensorFlow patch at module load:",e)});var T=Object.freeze({__proto__:null,applyTensorFlowPatch:S});const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;let E;N&&(N.TextEncoder||(N.TextEncoder=TextEncoder),N.TextDecoder||(N.TextDecoder=TextDecoder),N.__TextEncoder__=TextEncoder,N.__TextDecoder__=TextDecoder),S(),console.log("Applied TensorFlow.js patch via ES modules in setup.ts");const $=new Uint8Array(16);function C(){if(!E&&(E="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!E))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return E($)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));var A={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _(e,t,n){if(A.randomUUID&&!e)return A.randomUUID();const r=(e=e||{}).random||(e.rng||C)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]}(r)}const O=(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)},F=(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))},D=(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)},M=(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 P(e,t,n=O){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))}}const B=new Map;function L(e,t){if(g())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 l;if(B.size<4)l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Add isFloat32Array and isTypedArray directly to util\n isFloat32Array: (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr &&\n Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n },\n isTypedArray: (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n },\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\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}}),B.set(c,l);else{const n=Array.from(B.keys()),r=n[Math.floor(Math.random()*n.length)];l=B.get(r),l._busy&&(l.terminate(),l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\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}}),B.set(r,l)),l._busy=!0}l.on("message",e=>{l._busy=!1,n(e.result)}),l.on("error",e=>{l._busy=!1,r(e)}),l.on("exit",e=>{0!==e&&(l._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(m()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{let a,s="./worker.js";try{if(void 0!==import.meta&&import.meta.url){s=`${import.meta.url.substring(0,import.meta.url.lastIndexOf("/")+1)}worker.js`}else if("undefined"!=typeof document){const e=document.getElementsByTagName("script");for(let t=0;t<e.length;t++){const n=e[t].src;if(n&&n.includes("unified.js")){s=n.substring(0,n.lastIndexOf("/")+1)+"worker.js";break}}}}catch(e){console.warn("Could not determine worker path from import.meta.url, using relative path",e)}if("./worker.js"===s&&"undefined"!=typeof window){const e=window.location.href,t=e.substring(0,e.lastIndexOf("/")+1);if(s=`${t}worker.js`,"undefined"!=typeof document){const e=`${t}dist/worker.js`,n=new XMLHttpRequest;n.open("HEAD",e,!1);try{n.send(),n.status>=200&&n.status<300&&(s=e)}catch(e){}}}console.log("Using worker path:",s);try{a=new Worker(s)}catch(s){console.warn("Failed to create Web Worker from file, trying inline worker:",s);try{const e=new Blob(["\n // Brainy Inline Worker Script\n console.log('Brainy Inline Worker: Started');\n\n self.onmessage = function (e) {\n try {\n console.log('Brainy Inline Worker: Received message', e.data ? 'with data' : 'without data');\n\n if (!e.data || !e.data.fnString) {\n throw new Error('Invalid message: missing function string');\n }\n\n console.log('Brainy Inline Worker: Creating function from string');\n const fn = new Function('return ' + e.data.fnString)();\n\n console.log('Brainy Inline Worker: Executing function with args');\n const result = fn(e.data.args);\n\n console.log('Brainy Inline Worker: Function executed successfully, posting result');\n self.postMessage({ result: result });\n } catch (error) {\n console.error('Brainy Inline Worker: Error executing function', error);\n self.postMessage({ \n error: error.message,\n stack: error.stack\n });\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);a=new Worker(t),console.log("Created inline worker using Blob URL")}catch(a){console.warn("Failed to create inline Web Worker, falling back to main thread execution:",a);try{const r=new Function("return "+e)();return void n(r(t))}catch(e){return void r(e)}}}const o=setTimeout(()=>{console.warn("Web Worker execution timed out, falling back to main thread"),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},25e3);a.onmessage=function(e){clearTimeout(o),e.data.error?r(new Error(e.data.error)):n(e.data.result),a.terminate()},a.onerror=function(s){clearTimeout(o),console.warn("Web Worker error, falling back to main thread execution:",s.message),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},a.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{let n;try{n=new Function("return "+e)()}catch(t){console.warn("Fallback: Error creating function with return syntax, trying alternative approaches",t);try{n=new Function("return ("+e+")")()}catch(r){console.warn("Fallback: Error creating function with parentheses wrapping",r);try{n=new Function(e)()}catch(r){console.warn("Fallback: Direct approach failed, trying with function wrapper",r);try{n=new Function("return function(args) { return ("+e+")(args); }")()}catch(e){throw console.error("Fallback: All approaches to create function failed",e),new Error("Failed to create function from string: "+t.message)}}}}return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function z(){g()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of B.values())e.terminate();B.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let W=class{constructor(e={}){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu",this.verbose=!0,this.verbose=void 0===e.verbose||e.verbose}addServerCompatibilityPolyfills(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};try{e.util||(e.util={}),e.util.isFloat32Array||(e.util.isFloat32Array=e=>!!(e instanceof Float32Array||e&&"[object Float32Array]"===Object.prototype.toString.call(e))),e.util.isTypedArray||(e.util.isTypedArray=e=>!(!ArrayBuffer.isView(e)||e instanceof DataView))}catch(e){console.warn("Failed to add utility polyfills:",e)}}isTestEnvironment(){return"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))}logger(e,t,...n){("error"===e||this.verbose)&&console[e](t,...n)}async loadModelWithRetry(e,t=3,n=1e3){let r=null;for(let a=0;a<=t;a++)try{this.logger("log",0===a?"Loading Universal Sentence Encoder model...":`Retrying Universal Sentence Encoder model loading (attempt ${a+1}/${t+1})...`);const n=await e();return a>0&&this.logger("log","Universal Sentence Encoder model loaded successfully after retry"),n}catch(e){r=e;const s=r.message||String(r),o=s.includes("Failed to parse model JSON")||s.includes("Failed to fetch")||s.includes("Network error")||s.includes("ENOTFOUND")||s.includes("ECONNRESET")||s.includes("ETIMEDOUT")||s.includes("JSON")||s.includes("model.json");if(!(a<t&&o))throw a>=t?this.logger("error",`Universal Sentence Encoder model loading failed after ${t+1} attempts. Last error: ${s}`):this.logger("error",`Universal Sentence Encoder model loading failed with non-retryable error: ${s}`),r;{const e=n*Math.pow(2,a);this.logger("warn",`Universal Sentence Encoder model loading failed (attempt ${a+1}): ${s}. Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e))}}throw r||new Error("Unknown error during model loading")}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.addServerCompatibilityPolyfills();try{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;if(e)try{if("undefined"!=typeof process&&process.versions&&process.versions.node){const t=await Promise.resolve().then(function(){return Ft});e.TextEncoder||(e.TextEncoder=t.TextEncoder),e.TextDecoder||(e.TextDecoder=t.TextDecoder)}}catch(t){e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder)}const{applyTensorFlowPatch:t}=await Promise.resolve().then(function(){return T});await t(),this.tf=await Promise.resolve().then(function(){return ky}),await Promise.resolve().then(function(){return aS});try{if("undefined"!=typeof window){await Promise.resolve().then(function(){return MO});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.use=await Promise.resolve().then(function(){return gD})}catch(e){throw this.logger("error","Failed to initialize TensorFlow.js:",e),e}this.tf.setBackend&&await this.tf.setBackend(this.backend);const t=function(e){let t=null;if(e.load&&"function"==typeof e.load)t=e.load;else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load;else if(e.default&&"function"==typeof e.default)t=e.default;else if("function"==typeof e)t=e;else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load;else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.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];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];break}}if(t)break}return t}(this.use);if(!t)throw new Error("Could not find Universal Sentence Encoder load function");this.model=await this.loadModelWithRetry(t),this.initialized=!0,console.warn=e}catch(e){throw this.logger("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 this.logger("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 this.logger("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){this.logger("error","Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function V(e,t,n=[],r=!0){"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))||console[e](t,...n)}function U(e){return e?async t=>await e.embed(t):q()}let G=null,j=!1,H=!0;function q(e={}){return void 0!==e.verbose&&(H=e.verbose),G||(G=new W({verbose:H})),async e=>{try{if(!j)try{await G.init(),j=!0}catch(e){throw j=!1,e}return await G.embed(e)}catch(e){throw V("error","Failed to use TensorFlow embedding:",[e],H),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}function K(e={}){return q(e)}const X=K();let Y=null,Q=!1,J=!0;function Z(e={}){return void 0!==e.verbose&&(J=e.verbose),Y||(Y=new W({verbose:J})),async e=>{try{return Q||(await Y.init(),Q=!0),await Y.embedBatch(e)}catch(e){throw V("error","Failed to use TensorFlow batch embedding:",[e],J),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}}}function ee(e={}){return Z(e)}const te=ee();function ne(e){const t=U(e);return async e=>{const n=t.toString();return await L(n,e)}}var re=Object.freeze({__proto__:null,UniversalSentenceEncoder:W,createBatchEmbeddingFunction:Z,createEmbeddingFunction:U,createTensorFlowEmbeddingFunction:q,createThreadedEmbeddingFunction:ne,defaultBatchEmbeddingFunction:te,defaultEmbeddingFunction:X,getDefaultBatchEmbeddingFunction:ee,getDefaultEmbeddingFunction:K});const ae={M:16,efConstruction:200,efSearch:50,ml:16};class se{constructor(e={},t=O,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...ae,...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 P(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 l=this.nouns.get(t);if(!l){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const u=l.connections.get(r)||new Set;if(this.useParallelization&&u.size>=10){const t=[];for(const e of u)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 u)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 oe={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class ie{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 ce extends se{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={...oe,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new ie(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 ie(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 le="nouns",ue="verbs",de="metadata",he="index";class pe{constructor(){this.isInitialized=!1}async ensureInitialized(){this.isInitialized||await this.init()}async saveNoun(e){return await this.ensureInitialized(),this.saveNode(e)}async getNoun(e){return await this.ensureInitialized(),this.getNode(e)}async getAllNouns(){return await this.ensureInitialized(),this.getAllNodes()}async getNounsByNounType(e){return await this.ensureInitialized(),this.getNodesByNounType(e)}async deleteNoun(e){return await this.ensureInitialized(),this.deleteNode(e)}async saveVerb(e){return await this.ensureInitialized(),this.saveEdge(e)}async getVerb(e){return await this.ensureInitialized(),this.getEdge(e)}async getAllVerbs(){return await this.ensureInitialized(),this.getAllEdges()}async getVerbsBySource(e){return await this.ensureInitialized(),this.getEdgesBySource(e)}async getVerbsByTarget(e){return await this.ensureInitialized(),this.getEdgesByTarget(e)}async getVerbsByType(e){return await this.ensureInitialized(),this.getEdgesByType(e)}async deleteVerb(e){return await this.ensureInitialized(),this.deleteEdge(e)}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}class fe extends pe{constructor(){super(),this.nouns=new Map,this.verbs=new Map,this.metadata=new Map}async init(){this.isInitialized=!0}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));this.nouns.set(e.id,t)}async getNode(e){const t=this.nouns.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllNodes(){const e=[];for(const[t,n]of this.nouns.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getNodesByNounType(e){const t=[];for(const[n,r]of this.nouns.entries()){const a=await this.getMetadata(n);if(a&&a.noun===e){const e={id:r.id,vector:[...r.vector],connections:new Map};for(const[t,n]of r.connections.entries())e.connections.set(t,new Set(n));t.push(e)}}return t}async deleteNode(e){this.nouns.delete(e)}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};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};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllEdges(){const e=[];for(const[t,n]of this.verbs.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){this.verbs.delete(e)}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 clear(){this.nouns.clear(),this.verbs.clear(),this.metadata.clear()}async getStorageStatus(){return{type:"memory",used:0,quota:null,details:{nodeCount:this.nouns.size,edgeCount:this.verbs.size,metadataCount:this.metadata.size}}}}async function me(e){return e.getFile()}class ge extends pe{constructor(){super(),this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.indexDir=null,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(le,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(ue,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(de,{create:!0}),this.indexDir=await this.rootDir.getDirectoryHandle(he,{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 saveNode(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.nounsDir.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 node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNode(e){await this.ensureInitialized();try{const t=await this.nounsDir.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(e){return null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.nounsDir.entries())if("file"===n.kind)try{const t=await me(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}catch(e){console.error(`Error reading node file ${t}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{for await(const[n,r]of this.nounsDir.entries())if("file"===r.kind)try{const n=await me(r),a=await n.text(),s=JSON.parse(a),o=await this.getMetadata(s.id);if(o&&o.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}catch(e){console.error(`Error reading node file ${n}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return t}async deleteNode(e){await this.ensureInitialized();try{await this.nounsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting node ${e}:`,t),t}}async saveEdge(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 edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getEdge(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(e){return null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.verbsDir.entries())if("file"===n.kind)try{const t=await me(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}catch(e){console.error(`Error reading edge file ${t}:`,e)}}catch(e){console.error("Error reading verbs directory:",e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting edge ${e}:`,t),t}}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 ${e}:`,t),new Error(`Failed to save metadata ${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(e){return null}}async clear(){await this.ensureInitialized();const e=async e=>{try{for await(const[t,n]of e.entries())await e.removeEntry(t)}catch(e){throw console.error("Error removing directory contents:",e),e}};try{await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}catch(e){throw console.error("Error clearing storage:",e),e}}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)),this.indexDir&&(e+=await t(this.indexDir));let r=null,a={isPersistent:await this.isPersistent(),nounTypes:{}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();r=e.quota||null,a={...a,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)}this.nounsDir&&(a.nounsCount=await n(this.nounsDir)),this.verbsDir&&(a.verbsCount=await n(this.verbsDir)),this.metadataDir&&(a.metadataCount=await n(this.metadataDir));const s={};if(this.metadataDir)for await(const[e,t]of this.metadataDir.entries())if("file"===t.kind)try{const e=await me(t),n=await e.text(),r=JSON.parse(n);r.noun&&(s[r.noun]=(s[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return a.nounTypes=s,{type:"opfs",used:e,quota:r,details:a}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}}let ye,be;try{const e=import("fs"),t=import("path");Promise.all([e,t]).then(([e,t])=>{ye=e,be=t.default}).catch(e=>{console.error("Failed to load Node.js modules:",e)})}catch(e){console.error("FileSystemStorage: Failed to load Node.js modules. This adapter is not supported in this environment.",e)}class xe extends pe{constructor(e){super(),this.rootDir=e,this.nounsDir=be.join(this.rootDir,le),this.verbsDir=be.join(this.rootDir,ue),this.metadataDir=be.join(this.rootDir,de),this.indexDir=be.join(this.rootDir,he)}async init(){if(!this.isInitialized){if(!ye||!be)throw new Error("FileSystemStorage requires a Node.js environment, but `fs` and `path` modules could not be loaded.");try{await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.indexDir),this.isInitialized=!0}catch(e){throw console.error("Error initializing FileSystemStorage:",e),e}}}async ensureDirectoryExists(e){try{await ye.promises.mkdir(e,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}async saveNode(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=be.join(this.nounsDir,`${e.id}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getNode(e){await this.ensureInitialized();const t=be.join(this.nounsDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8"),n=JSON.parse(e),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"ENOENT"!==t.code&&console.error(`Error reading node ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{const t=await ye.promises.readdir(this.nounsDir);for(const n of t)if(n.endsWith(".json")){const t=be.join(this.nounsDir,n),r=await ye.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{const n=await ye.promises.readdir(this.nounsDir);for(const r of n)if(r.endsWith(".json")){const n=be.join(this.nounsDir,r),a=await ye.promises.readFile(n,"utf-8"),s=JSON.parse(a),o=s.id,i=await this.getMetadata(o);if(i&&i.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return t}async deleteNode(e){await this.ensureInitialized();const t=be.join(this.nounsDir,`${e}.json`);try{await ye.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting node file ${t}:`,e),e}}async saveEdge(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=be.join(this.verbsDir,`${e.id}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getEdge(e){await this.ensureInitialized();const t=be.join(this.verbsDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8"),n=JSON.parse(e),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,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{const t=await ye.promises.readdir(this.verbsDir);for(const n of t)if(n.endsWith(".json")){const t=be.join(this.verbsDir,n),r=await ye.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.verbsDir}:`,e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();const t=be.join(this.verbsDir,`${e}.json`);try{await ye.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting edge file ${t}:`,e),e}}async saveMetadata(e,t){await this.ensureInitialized();const n=be.join(this.metadataDir,`${e}.json`);await ye.promises.writeFile(n,JSON.stringify(t,null,2))}async getMetadata(e){await this.ensureInitialized();const t=be.join(this.metadataDir,`${e}.json`);try{const e=await ye.promises.readFile(t,"utf-8");return JSON.parse(e)}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading metadata ${e}:`,t),null}}async clear(){await this.ensureInitialized();const e=async t=>{try{const n=await ye.promises.readdir(t);for(const r of n){const n=be.join(t,r);(await ye.promises.stat(n)).isDirectory()?(await e(n),await ye.promises.rmdir(n)):await ye.promises.unlink(n)}}catch(e){if("ENOENT"!==e.code)throw console.error(`Error removing directory contents ${t}:`,e),e}};await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await ye.promises.readdir(e);for(const a of r){const r=be.join(e,a),s=await ye.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){"ENOENT"!==t.code&&console.error(`Error calculating size for directory ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.indexDir);e=n+r+a+s;const o=(await ye.promises.readdir(this.nounsDir)).filter(e=>e.endsWith(".json")).length,i=(await ye.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).length,c=(await ye.promises.readdir(this.metadataDir)).filter(e=>e.endsWith(".json")).length,l={},u=await ye.promises.readdir(this.metadataDir);for(const e of u)if(e.endsWith(".json"))try{const t=be.join(this.metadataDir,e),n=await ye.promises.readFile(t,"utf-8"),r=JSON.parse(n);r.noun&&(l[r.noun]=(l[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return{type:"filesystem",used:e,quota:null,details:{rootDirectory:this.rootDir,nounsCount:o,verbsCount:i,metadataCount:c,nounsDirSize:n,verbsDirSize:r,metadataDirSize:a,indexDirSize:s,nounTypes:l}}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}}class we extends pe{constructor(e){super(),this.s3Client=null,this.bucketName=e.bucketName,this.region=e.region||"auto",this.endpoint=e.endpoint,this.accountId=e.accountId,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken,this.serviceType=e.serviceType||"s3",this.nounPrefix=`${le}/`,this.verbPrefix=`${ue}/`,this.metadataPrefix=`${de}/`,this.indexPrefix=`${he}/`}async init(){if(!this.isInitialized)try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={region:this.region,credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};this.sessionToken&&(t.credentials.sessionToken=this.sessionToken),this.endpoint&&(t.endpoint=this.endpoint),"r2"===this.serviceType&&this.accountId&&(t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`),this.s3Client=new e(t);const{HeadBucketCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName})),this.isInitialized=!0}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{console.log(`Saving node ${e.id} to bucket ${this.bucketName}`);const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.nounPrefix}${e.id}.json`,a=JSON.stringify(t,null,2);console.log(`Saving node to key: ${r}`),console.log(`Node data: ${a.substring(0,100)}${a.length>100?"...":""}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Node ${e.id} saved successfully:`,s);const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));t&&t.Body?console.log(`Verified node ${e.id} was saved correctly`):console.error(`Failed to verify node ${e.id} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify node ${e.id} was saved correctly:`,t)}}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{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting node ${e} from bucket ${this.bucketName}`);const n=`${this.nounPrefix}${e}.json`;console.log(`Looking for node at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No node found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed node data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections))return console.error(`Invalid node data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n};return console.log(`Successfully retrieved node ${e}:`,r),r}catch(t){return console.error(`Failed to parse node data for ${e}:`,t),null}}catch(t){return console.log(`Error getting node for ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting all nodes from bucket ${this.bucketName} with prefix ${this.nounPrefix}`);const n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.nounPrefix})),r=[];if(!n||!n.Contents||0===n.Contents.length)return console.log(`No nodes found in bucket ${this.bucketName} with prefix ${this.nounPrefix}`),r;console.log(`Found ${n.Contents.length} nodes in bucket ${this.bucketName}`),console.log("Keys found:");for(const e of n.Contents)e&&e.Key&&console.log(`- ${e.Key}`);const a=n.Contents.map(async e=>{if(!e||!e.Key)return console.log("Skipping undefined object or object without Key"),null;try{const n=e.Key.replace(this.nounPrefix,"").replace(".json","");console.log(`Getting node with ID ${n} from key ${e.Key}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}));if(!r||!r.Body)return console.log(`No response or response body for node ${n}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body for ${n}: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const e=JSON.parse(a);if(console.log(`Parsed node data for ${n}:`,e),!(e&&e.id&&e.vector&&e.connections))return console.error(`Invalid node data for ${n}:`,e),null;const t=new Map;for(const[n,r]of Object.entries(e.connections))t.set(Number(n),new Set(r));const r={id:e.id,vector:e.vector,connections:t};return console.log(`Successfully retrieved node ${n}:`,r),r}catch(e){return console.error(`Failed to parse node data for ${n}:`,e),null}}catch(t){return console.error(`Error getting node from ${e.Key}:`,t),null}}),s=(await Promise.all(a)).filter(e=>null!==e);console.log(`Returning ${s.length} nodes`);for(const e of s)console.log(`- Node ${e.id}`);return s}catch(e){return console.error("Failed to get all nodes:",e),[]}}async getNodesByNounType(e){await this.ensureInitialized();try{const t=await this.getAllNodes(),n=[];for(const r of t){const t=await this.getMetadata(r.id);t&&t.noun===e&&n.push(r)}return n}catch(t){return console.error(`Failed to get nodes by noun type ${e}:`,t),[]}}async deleteNode(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.nounPrefix}${e}.json`}))}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:`${this.verbPrefix}${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");console.log(`Getting edge ${e} from bucket ${this.bucketName}`);const n=`${this.verbPrefix}${e}.json`;console.log(`Looking for edge at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No edge found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved edge body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed edge data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections&&t.sourceId&&t.targetId&&t.type))return console.error(`Invalid edge data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n,sourceId:t.sourceId,targetId:t.targetId,type:t.type,weight:t.weight||1,metadata:t.metadata||{}};return console.log(`Successfully retrieved edge ${e}:`,r),r}catch(t){return console.error(`Failed to parse edge data for ${e}:`,t),null}}catch(t){return console.log(`Error getting edge for ${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:this.verbPrefix})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{e.Key.replace(this.verbPrefix,"").replace(".json","");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(`Error getting edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){return console.error("Failed to get all edges:",e),[]}}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.verbPrefix}${e}.json`}))}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{console.log(`Saving metadata for ${e} to bucket ${this.bucketName}`);const{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.metadataPrefix}${e}.json`,a=JSON.stringify(t,null,2);console.log(`Saving metadata to key: ${r}`),console.log(`Metadata: ${a}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Metadata for ${e} saved successfully:`,s);const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));if(t&&t.Body){const n=await t.Body.transformToString();console.log(`Verified metadata for ${e} was saved correctly: ${n}`)}else console.error(`Failed to verify metadata for ${e} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify metadata for ${e} was saved correctly:`,t)}}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");console.log(`Getting metadata for ${e} from bucket ${this.bucketName}`);const n=`${this.metadataPrefix}${e}.json`;console.log(`Looking for metadata at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No metadata found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved metadata body: ${a}`);try{const t=JSON.parse(a);return console.log(`Successfully retrieved metadata for ${e}:`,t),t}catch(t){return console.error(`Failed to parse metadata for ${e}:`,t),null}}catch(t){if("NoSuchKey"===t.name||t.message&&(t.message.includes("NoSuchKey")||t.message.includes("not found")||t.message.includes("does not exist")))return console.log(`Metadata not found for ${e}`),null;throw console.error(`Error getting metadata for ${e}:`,t),t}}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=async n=>{const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:n}));if(r&&r.Contents&&0!==r.Contents.length)for(const e of r.Contents)e&&e.Key&&await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))};await n(this.nounPrefix),await n(this.verbPrefix),await n(this.metadataPrefix),await n(this.indexPrefix)}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");let t=0,n=0,r=0,a=0;const s=async t=>{let n=0,r=0;const a=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:t}));if(!a||!a.Contents||0===a.Contents.length)return{size:n,count:r};for(const e of a.Contents)if(e){n+=("number"==typeof e.Size?e.Size:e.Size?parseInt(e.Size.toString(),10):0)||0,r++,0===n&&r>0&&(n=100*r)}return{size:n,count:r}},o=await s(this.nounPrefix),i=await s(this.verbPrefix),c=await s(this.metadataPrefix),l=await s(this.indexPrefix);t=o.size+i.size+c.size+l.size,n=o.count,r=i.count,a=c.count,0===t&&(n>0||r>0||a>0)&&(console.log(`Setting minimum size for ${n} nodes, ${r} edges, and ${a} metadata objects`),t=100*(n+r+a)),(n>0||r>0||a>0)&&(console.log(`Ensuring positive size for storage status with ${n} nodes, ${r} edges, and ${a} metadata objects`),t=Math.max(t,1));const u={},d=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.metadataPrefix}));if(d&&d.Contents){const{GetObjectCommand:e}=await import("@aws-sdk/client-s3");for(const t of d.Contents)if(t&&t.Key)try{const n=await this.s3Client.send(new e({Bucket:this.bucketName,Key:t.Key}));if(n&&n.Body){const e=await n.Body.transformToString();try{const t=JSON.parse(e);t&&t.noun&&(u[t.noun]=(u[t.noun]||0)+1)}catch(e){console.error(`Failed to parse metadata from ${t.Key}:`,e)}}}catch(e){console.error(`Error getting metadata from ${t.Key}:`,e)}}return{type:this.serviceType,used:t,quota:null,details:{bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,nodeCount:n,edgeCount:r,metadataCount:a,nounTypes:u}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}}async function ve(e={}){if(e.forceMemoryStorage)return console.log("Using memory storage (forced)"),new fe;if(e.forceFileSystemStorage)return console.log("Using file system storage (forced)"),new xe(e.rootDirectory||"./brainy-data");if(e.type&&"auto"!==e.type)switch(e.type){case"memory":return console.log("Using memory storage"),new fe;case"opfs":{const t=new ge;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}return console.warn("OPFS storage is not available, falling back to memory storage"),new fe}case"filesystem":return console.log("Using file system storage"),new xe(e.rootDirectory||"./brainy-data");case"s3":return e.s3Storage?(console.log("Using Amazon S3 storage"),new we({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"})):(console.warn("S3 storage configuration is missing, falling back to memory storage"),new fe);case"r2":return e.r2Storage?(console.log("Using Cloudflare R2 storage"),new we({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"})):(console.warn("R2 storage configuration is missing, falling back to memory storage"),new fe);case"gcs":return e.gcsStorage?(console.log("Using Google Cloud Storage"),new we({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"})):(console.warn("GCS storage configuration is missing, falling back to memory storage"),new fe);default:return console.warn(`Unknown storage type: ${e.type}, falling back to memory storage`),new fe}if(e.customS3Storage)return console.log(`Using custom S3-compatible storage: ${e.customS3Storage.serviceType||"custom"}`),new we({bucketName:e.customS3Storage.bucketName,region:e.customS3Storage.region,endpoint:e.customS3Storage.endpoint,accessKeyId:e.customS3Storage.accessKeyId,secretAccessKey:e.customS3Storage.secretAccessKey,serviceType:e.customS3Storage.serviceType||"custom"});if(e.r2Storage)return console.log("Using Cloudflare R2 storage"),new we({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"});if(e.s3Storage)return console.log("Using Amazon S3 storage"),new we({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"});if(e.gcsStorage)return console.log("Using Google Cloud Storage"),new we({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"});const t=new ge;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage (auto-detected)"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}try{if("undefined"!=typeof process&&process.versions&&process.versions.node)return console.log("Using file system storage (auto-detected)"),new xe(e.rootDirectory||"./brainy-data")}catch(e){}return console.log("Using memory storage (auto-detected)"),new fe}const ke={Person:"person",Place:"place",Thing:"thing",Event:"event",Concept:"concept",Content:"content",Group:"group",List:"list",Category:"category"},Ie={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 Se;!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"}(Se||(Se={}));class Te{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 Ne extends Te{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 Se.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:_(),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:_(),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=_(),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 Ee extends Te{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 Se.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=_();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=_();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:_(),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:_(),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=_(),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 $e(e,t,n={}){switch(e){case"websocket":const n=new Ne(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new Ee(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class Ce extends Ne{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 Re{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 Se.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 Ae(e,t={}){const n=new Ce(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new Re(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 _e{get dimensions(){return this._dimensions}get maxConnections(){return this.index.getConfig().M||16}get efConstruction(){return this.index.getConfig().efConstruction||200}constructor(e={}){if(this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.loggingConfig={verbose:!0},this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,void 0!==e.dimensions&&e.dimensions<=0)throw new Error("Dimensions must be a positive number");this._dimensions=e.dimensions||512,this.distanceFunction=e.distanceFunction||F,e.hnswOptimized?(this.index=new ce(e.hnswOptimized,this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0):this.index=new se(e.hnsw,this.distanceFunction),this.storage=e.storageAdapter||null,void 0!==e.logging&&(this.loggingConfig={...this.loggingConfig,...e.logging}),e.embeddingFunction?this.embeddingFunction=e.embeddingFunction:this.embeddingFunction=K({verbose:this.loggingConfig?.verbose}),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{await this.embeddingFunction("")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e);try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return re}),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){let e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};if(e.s3Storage)if(e.s3Storage.bucketName&&e.s3Storage.accessKeyId&&e.s3Storage.secretAccessKey);else{const{s3Storage:t,...n}=e;e=n,console.warn("Ignoring s3Storage configuration due to missing required fields")}this.storage=await ve(e)}await this.storage.init(),this.useOptimizedIndex&&this.index instanceof ce&&this.index.setStorage(this.storage);const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)t.vector.length===this._dimensions?await this.index.addItem({id:t.id,vector:t.vector}):console.warn(`Skipping noun ${t.id} due to dimension mismatch: expected ${this._dimensions}, got ${t.vector.length}`);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 Ae(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");if(r.length!==this._dimensions)throw new Error(`Vector dimension mismatch: expected ${this._dimensions}, got ${r.length}`);const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:_());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(ke).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ke.Concept)}let e=t;t&&"object"==typeof t&&(e={...t,id:a}),await this.storage.saveMetadata(a,e)}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 addItem(e,t,n={}){return this.add(e,t,{...n,forceEmbed:!0})}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 te(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const l=await Promise.all([...i,...c]);r.push(...l)}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={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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;let r=await this.storage.getMetadata(e);null===r&&(r={}),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;let a=await this.storage.getMetadata(t);null===a&&(a={}),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(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");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(ke).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=ke.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{let a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a&&r.autoCreateMissingNouns)try{const t=new Array(this._dimensions).fill(0),n=r.missingNounMetadata||{autoCreated:!0,createdAt:(new Date).toISOString(),noun:ke.Concept};await this.add(t,n,{id:e}),a=this.index.getNouns().get(e),console.warn(`Auto-created missing source noun with ID ${e}`)}catch(t){throw console.error(`Failed to auto-create source noun with ID ${e}:`,t),new Error(`Failed to auto-create source noun with ID ${e}: ${t}`)}if(!s&&r.autoCreateMissingNouns)try{const e=new Array(this._dimensions).fill(0),n=r.missingNounMetadata||{autoCreated:!0,createdAt:(new Date).toISOString(),noun:ke.Concept};await this.add(e,n,{id:t}),s=this.index.getNouns().get(t),console.warn(`Auto-created missing target noun with ID ${t}`)}catch(e){throw console.error(`Failed to auto-create target noun with ID ${t}:`,e),new Error(`Failed to auto-create target noun with ID ${t}: ${e}`)}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||_();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(Ie).includes(c)||(console.warn(`Invalid verb type: ${c}. Using RelatedTo as default.`),c=Ie.RelatedTo)}const l={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 u=this.index.getNouns().get(o);if(!u)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);return l.connections=u.connections,await this.storage.saveVerb(l),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()}async getStatistics(){await this.ensureInitialized();try{const e=this.index.getNouns().size,t=(await this.storage.getAllVerbs()).length;let n=0;const r=this.index.getNouns();for(const[e]of r.entries())try{const t=await this.storage.getMetadata(e);null!=t&&n++}catch(e){}return{nounCount:e,verbCount:t,metadataCount:n,hnswIndexSize:this.index.size()}}catch(e){throw console.error("Failed to get statistics:",e),new Error(`Failed to get statistics: ${e}`)}}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 ce){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(),z(),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(ke),r=Object.values(Ie),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||Ie.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 se(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(ke),a=e.verbTypes||Object.values(Ie);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[ke.Person]:"A person with unique characteristics",[ke.Place]:"A location with specific attributes",[ke.Thing]:"An object with distinct properties",[ke.Event]:"An occurrence with temporal aspects",[ke.Concept]:"An abstract idea or notion",[ke.Content]:"A piece of content or information",[ke.Group]:"A collection of related entities",[ke.List]:"An ordered sequence of items",[ke.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={[Ie.AttributedTo]:"Attribution relationship",[Ie.Controls]:"Control relationship",[Ie.Created]:"Creation relationship",[Ie.Earned]:"Achievement relationship",[Ie.Owns]:"Ownership relationship",[Ie.MemberOf]:"Membership relationship",[Ie.RelatedTo]:"General relationship",[Ie.WorksWith]:"Collaboration relationship",[Ie.FriendOf]:"Friendship relationship",[Ie.ReportsTo]:"Reporting relationship",[Ie.Supervises]:"Supervision relationship",[Ie.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],l=a[Math.floor(Math.random()*a.length)],u={verb:l,description:i[l]||`A random ${l} 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:l,weight:u.weight,metadata:u});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 Oe=null;const Fe=[];function De(e){return void 0===e.enabled&&(e.enabled=!0),Fe.push(e),e}function Me(e){const t=e||Oe;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Fe)e.enabled&&t.register(e);return t}function Pe(e,t){const n=Fe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function Be(e){return Fe.filter(t=>{switch(e){case Se.SENSE:return"processRawData"in t&&"listenToFeed"in t;case Se.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case Se.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case Se.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case Se.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case Se.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case Se.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case Se.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class Le{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 ze(e){const t=new Le(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&&(De(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function We(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 Ve(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 Ue(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&&(De(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 Ge;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(Ge||(Ge={}));const je={mode:Ge.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class He{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 Se.SENSE:return[...this.registry.sense];case Se.CONDUIT:return[...this.registry.conduit];case Se.COGNITION:return[...this.registry.cognition];case Se.MEMORY:return[...this.registry.memory];case Se.PERCEPTION:return[...this.registry.perception];case Se.DIALOG:return[...this.registry.dialog];case Se.ACTIVATION:return[...this.registry.activation];case Se.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Se.SENSE),this.registry.conduit.length>0&&e.push(Se.CONDUIT),this.registry.cognition.length>0&&e.push(Se.COGNITION),this.registry.memory.length>0&&e.push(Se.MEMORY),this.registry.perception.length>0&&e.push(Se.PERCEPTION),this.registry.dialog.length>0&&e.push(Se.DIALOG),this.registry.activation.length>0&&e.push(Se.ACTIVATION),this.registry.webSocket.length>0&&e.push(Se.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===Ge.THREADED)&&v())}async execute(e,t,n=[],r={}){const a={...je,...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=L(((...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 Ve(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 Ge.PARALLEL:case Ge.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case Ge.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case Ge.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 Ge.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 Ve(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(Se.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(Se.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(Se.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(Se.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(Se.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(Se.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(Se.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const qe=new He;!function(e){Oe=e}(qe);const Ke=qe,Xe=(e,t,n=[],r={})=>qe.execute(e,t,n,r),Ye=(e,t,n=[],r={})=>qe.executeByType(e,t,n,r),Qe=(e,t,...n)=>qe.executeSingle(e,t,...n),Je=(e,t,n={})=>qe.processStaticData(e,t,n),Ze=(e,t,n,r,a,s={})=>qe.processStreamingData(e,t,n,r,a,s),et=(e,t={})=>qe.createPipeline(e,t),tt=(e,t,n,r={})=>qe.createStreamingPipeline(e,t,n,r),nt=Ge;var rt;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(rt||(rt={}));const at={mode:rt.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const st=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={...at,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...at,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...at,...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 Se.SENSE:return[...this.registry.sense];case Se.CONDUIT:return[...this.registry.conduit];case Se.COGNITION:return[...this.registry.cognition];case Se.MEMORY:return[...this.registry.memory];case Se.PERCEPTION:return[...this.registry.perception];case Se.DIALOG:return[...this.registry.dialog];case Se.ACTIVATION:return[...this.registry.activation];case Se.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Se.SENSE),this.registry.conduit.length>0&&e.push(Se.CONDUIT),this.registry.cognition.length>0&&e.push(Se.COGNITION),this.registry.memory.length>0&&e.push(Se.MEMORY),this.registry.perception.length>0&&e.push(Se.PERCEPTION),this.registry.dialog.length>0&&e.push(Se.DIALOG),this.registry.activation.length>0&&e.push(Se.ACTIVATION),this.registry.webSocket.length>0&&e.push(Se.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===rt.THREADED)&&v())}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=L(((...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 rt.PARALLEL:return a.map(s);case rt.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 rt.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case rt.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case rt.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 ot,it,ct;const lt=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(ot=globalThis.TransformStream,it=globalThis.ReadableStream,ct=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{ot=e.TransformStream,it=e.ReadableStream,ct=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+.")}),ut={timeout:3e4,stopOnError:!1};class dt{constructor(e={}){this.brainyData=e.brainyData||new _e}async ensureStreamClassesInitialized(){await lt}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...ut,...n},a={success:!0,data:null,stageResults:{}};try{const n=await st.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=st.getAugmentationsByType(Se.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)}`,l=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!l.success)return{success:!1,data:null,error:`Failed to store data: ${l.error}`,stageResults:{...a.stageResults,memory:l}};a.stageResults.memory=l;const u=await st.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of u){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await st.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 st.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 st.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 ot({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 ct({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=st.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new it({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 ct({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 ot({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new ct({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const l=s;return l.readableStream=o,l.writableStream=c,l}}const ht=new dt,pt={autoInitialize:!1,debug:!1};async function ft(e,t={}){const n={...pt,...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=mt(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=De(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 mt(e){const t=[];if(gt(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(gt(r)&&t.push(r),Array.isArray(r)&&r.every(gt)&&t.push(...r))}return t}function gt(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function yt(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function bt(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class xt{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-F(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 wt extends xt{constructor(e){super(e,new fe),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return Se.MEMORY}}class vt extends xt{constructor(e,t){super(e,new xe(t||".")),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return Se.MEMORY}}class kt extends xt{constructor(e){super(e,new ge),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return Se.MEMORY}}async function It(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new wt(e);case"filesystem":return new vt(e,t.rootDirectory);case"opfs":return new kt(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new vt(e,t.rootDirectory);{const n=new ge;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new kt(e)):new wt(e)}}const St="1.0.0";var Tt;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}(Tt||(Tt={}));class Nt{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:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class Et{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=st.getAvailableAugmentationTypes();for(const n of t){const t=st.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 Se.SENSE:return await st.executeSensePipeline(t,r,a);case Se.CONDUIT:return await st.executeConduitPipeline(t,r,a);case Se.COGNITION:return await st.executeCognitionPipeline(t,r,a);case Se.MEMORY:return await st.executeMemoryPipeline(t,r,a);case Se.PERCEPTION:return await st.executePerceptionPipeline(t,r,a);case Se.DIALOG:return await st.executeDialogPipeline(t,r,a);case Se.ACTIVATION:return await st.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(Se).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class $t{constructor(e,t={}){this.dataAdapter=new Nt(e),this.toolset=new Et,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case Tt.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case Tt.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case Tt.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case Tt.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:St,environment:m()?"browser":g()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:St});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=_(),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:St,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:St,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=a.Buffer);const Ct={get isBrowser(){return m()},get isNode(){return g()},get isServerless(){return!m()&&!g()}};"undefined"!=typeof globalThis&&(globalThis.__ENV__=Ct),console.log(`Brainy running in ${Ct.isBrowser?"browser":Ct.isNode?"Node.js":"serverless/unknown"} environment`);const Rt=globalThis.TextEncoder||"undefined"!=typeof global&&global.TextEncoder||class{encode(e){return new Uint8Array(Buffer.from(e,"utf8"))}},At=globalThis.TextDecoder||"undefined"!=typeof global&&global.TextDecoder||class{decode(e){return Buffer.from(e).toString("utf8")}},_t={isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray};var Ot={TextEncoder:Rt,TextDecoder:At,types:_t};var Ft=Object.freeze({__proto__:null,TextDecoder:At,TextEncoder:Rt,default:Ot,promises:{},types:_t});
10
10
  /**
11
11
  * @license
12
12
  * Copyright 2020 Google LLC. All Rights Reserved.