holosphere 2.0.0-alpha2 → 2.0.0-alpha5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/2019-D2OG2idw.js +6680 -0
- package/dist/2019-D2OG2idw.js.map +1 -0
- package/dist/2019-EION3wKo.cjs +8 -0
- package/dist/2019-EION3wKo.cjs.map +1 -0
- package/dist/_commonjsHelpers-C37NGDzP.cjs +2 -0
- package/dist/_commonjsHelpers-C37NGDzP.cjs.map +1 -0
- package/dist/_commonjsHelpers-CUmg6egw.js +7 -0
- package/dist/_commonjsHelpers-CUmg6egw.js.map +1 -0
- package/dist/browser-BSniCNqO.js +3058 -0
- package/dist/browser-BSniCNqO.js.map +1 -0
- package/dist/browser-Cq59Ij19.cjs +2 -0
- package/dist/browser-Cq59Ij19.cjs.map +1 -0
- package/dist/cjs/holosphere.cjs +1 -1
- package/dist/esm/holosphere.js +50 -53
- package/dist/index-BG8FStkt.cjs +12 -0
- package/dist/index-BG8FStkt.cjs.map +1 -0
- package/dist/index-Bbey4GkP.js +37869 -0
- package/dist/index-Bbey4GkP.js.map +1 -0
- package/dist/index-Cp3xctq8.js +15104 -0
- package/dist/index-Cp3xctq8.js.map +1 -0
- package/dist/index-hfVGRwSr.cjs +5 -0
- package/dist/index-hfVGRwSr.cjs.map +1 -0
- package/dist/indexeddb-storage-BD70pN7q.cjs +2 -0
- package/dist/indexeddb-storage-BD70pN7q.cjs.map +1 -0
- package/dist/{indexeddb-storage-CMW4qRQS.js → indexeddb-storage-Bjg84U5R.js} +49 -13
- package/dist/indexeddb-storage-Bjg84U5R.js.map +1 -0
- package/dist/{memory-storage-DQzcAZlf.js → memory-storage-CD0XFayE.js} +6 -2
- package/dist/memory-storage-CD0XFayE.js.map +1 -0
- package/dist/{memory-storage-DmePEP2q.cjs → memory-storage-DmMyJtOo.cjs} +2 -2
- package/dist/memory-storage-DmMyJtOo.cjs.map +1 -0
- package/dist/{secp256k1-vOXp40Fx.js → secp256k1-69sS9O-P.js} +2 -393
- package/dist/secp256k1-69sS9O-P.js.map +1 -0
- package/dist/secp256k1-TcN6vWGh.cjs +12 -0
- package/dist/secp256k1-TcN6vWGh.cjs.map +1 -0
- package/docs/CONTRACTS.md +797 -0
- package/examples/demo.html +47 -0
- package/package.json +10 -5
- package/src/contracts/abis/Appreciative.json +1280 -0
- package/src/contracts/abis/AppreciativeFactory.json +101 -0
- package/src/contracts/abis/Bundle.json +1435 -0
- package/src/contracts/abis/BundleFactory.json +106 -0
- package/src/contracts/abis/Holon.json +881 -0
- package/src/contracts/abis/Holons.json +330 -0
- package/src/contracts/abis/Managed.json +1262 -0
- package/src/contracts/abis/ManagedFactory.json +149 -0
- package/src/contracts/abis/Membrane.json +261 -0
- package/src/contracts/abis/Splitter.json +1624 -0
- package/src/contracts/abis/SplitterFactory.json +220 -0
- package/src/contracts/abis/TestToken.json +321 -0
- package/src/contracts/abis/Zoned.json +1461 -0
- package/src/contracts/abis/ZonedFactory.json +154 -0
- package/src/contracts/chain-manager.js +375 -0
- package/src/contracts/deployer.js +443 -0
- package/src/contracts/event-listener.js +507 -0
- package/src/contracts/holon-contracts.js +344 -0
- package/src/contracts/index.js +83 -0
- package/src/contracts/networks.js +224 -0
- package/src/contracts/operations.js +670 -0
- package/src/contracts/queries.js +589 -0
- package/src/core/holosphere.js +453 -1
- package/src/crypto/nostr-utils.js +263 -0
- package/src/federation/handshake.js +455 -0
- package/src/federation/hologram.js +1 -1
- package/src/hierarchical/upcast.js +6 -5
- package/src/index.js +463 -1939
- package/src/lib/ai-methods.js +308 -0
- package/src/lib/contract-methods.js +293 -0
- package/src/lib/errors.js +23 -0
- package/src/lib/federation-methods.js +238 -0
- package/src/lib/index.js +26 -0
- package/src/spatial/h3-operations.js +2 -2
- package/src/storage/backends/gundb-backend.js +377 -46
- package/src/storage/global-tables.js +28 -1
- package/src/storage/gun-auth.js +303 -0
- package/src/storage/gun-federation.js +776 -0
- package/src/storage/gun-references.js +198 -0
- package/src/storage/gun-schema.js +291 -0
- package/src/storage/gun-wrapper.js +347 -31
- package/src/storage/indexeddb-storage.js +49 -11
- package/src/storage/memory-storage.js +5 -0
- package/src/storage/nostr-async.js +194 -37
- package/src/storage/nostr-client.js +580 -51
- package/src/storage/persistent-storage.js +6 -1
- package/src/storage/unified-storage.js +119 -0
- package/src/subscriptions/manager.js +1 -1
- package/types/index.d.ts +133 -0
- package/dist/index-CDfIuXew.js +0 -15974
- package/dist/index-CDfIuXew.js.map +0 -1
- package/dist/index-ifOgtDvd.cjs +0 -3
- package/dist/index-ifOgtDvd.cjs.map +0 -1
- package/dist/indexeddb-storage-CMW4qRQS.js.map +0 -1
- package/dist/indexeddb-storage-DLZOgetM.cjs +0 -2
- package/dist/indexeddb-storage-DLZOgetM.cjs.map +0 -1
- package/dist/memory-storage-DQzcAZlf.js.map +0 -1
- package/dist/memory-storage-DmePEP2q.cjs.map +0 -1
- package/dist/secp256k1-CP0ZkpAx.cjs +0 -13
- package/dist/secp256k1-CP0ZkpAx.cjs.map +0 -1
- package/dist/secp256k1-vOXp40Fx.js.map +0 -1
package/dist/index-ifOgtDvd.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;const e=require("nostr-tools"),t=require("h3-js"),n=require("ajv");function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const r=s(t);class i{constructor(e,t={}){this.storage=e,this.queuePrefix="_outbox/",this.maxRetries=t.maxRetries||5,this.baseDelay=t.baseDelay||1e3,this.maxDelay=t.maxDelay||6e4,this.failedTTL=t.failedTTL||864e5}async enqueue(e,t){const n={id:e.id,event:e,relays:t,status:"pending",retries:0,createdAt:Date.now(),nextRetryAt:Date.now(),failedRelays:[]},s=`${this.queuePrefix}${e.id}`;return await this.storage.put(s,n),n}async markSent(e,t){const n=`${this.queuePrefix}${e}`,s=await this.storage.get(n);s&&(t.length>0?await this.storage.delete(n):await this._scheduleRetry(n,s))}async _scheduleRetry(e,t){if(t.retries++,t.retries>=this.maxRetries)t.status="failed",t.failedAt=Date.now();else{t.status="pending";const e=Math.min(this.baseDelay*Math.pow(2,t.retries)+1e3*Math.random(),this.maxDelay);t.nextRetryAt=Date.now()+e}await this.storage.put(e,t)}async getPendingEvents(){const e=await this.storage.getAll(this.queuePrefix),t=Date.now();return e.filter(e=>e&&"pending"===e.status&&e.nextRetryAt<=t).sort((e,t)=>e.createdAt-t.createdAt)}async getFailedEvents(){return(await this.storage.getAll(this.queuePrefix)).filter(e=>e&&"failed"===e.status)}async getStats(){const e=await this.storage.getAll(this.queuePrefix),t={total:e.length,pending:0,failed:0,oldestPending:null,oldestFailed:null};for(const n of e)n&&("pending"===n.status?(t.pending++,(!t.oldestPending||n.createdAt<t.oldestPending)&&(t.oldestPending=n.createdAt)):"failed"===n.status&&(t.failed++,(!t.oldestFailed||n.failedAt<t.oldestFailed)&&(t.oldestFailed=n.failedAt)));return t}async purgeOldFailed(e=this.failedTTL){const t=await this.storage.getAll(this.queuePrefix),n=Date.now();let s=0;for(const r of t)r&&"failed"===r.status&&n-r.failedAt>e&&(await this.storage.delete(`${this.queuePrefix}${r.id}`),s++);return s}async clear(){const e=await this.storage.getAll(this.queuePrefix);let t=0;for(const n of e)n&&n.id&&(await this.storage.delete(`${this.queuePrefix}${n.id}`),t++);return t}async retryFailed(e){const t=`${this.queuePrefix}${e}`,n=await this.storage.get(t);return n&&"failed"===n.status?(n.status="pending",n.retries=0,n.nextRetryAt=Date.now(),delete n.failedAt,await this.storage.put(t,n),n):null}}class o{constructor(e,t={}){this.client=e,this.interval=t.interval||1e4,this.running=!1,this.timer=null,this._processing=!1,t.autoStart&&this.start()}start(){this.running||(this.running=!0,this._scheduleNextRun())}stop(){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}isRunning(){return this.running}async syncNow(){return this._processOutbox()}_scheduleNextRun(){this.running&&(this.timer=setTimeout(()=>{this._runLoop()},this.interval))}async _runLoop(){if(this.running){try{await this._processOutbox()}catch(e){console.warn("[sync] Outbox processing failed:",e.message)}this._scheduleNextRun()}}async _processOutbox(){if(this._processing)return{skipped:!0,reason:"already processing"};this._processing=!0;const e={processed:0,succeeded:0,failed:0,purged:0};try{if(!this.client.outboxQueue)return{...e,skipped:!0,reason:"no outbox queue"};const n=await this.client.outboxQueue.getPendingEvents();e.processed=n.length;for(const s of n)try{(await this.client._attemptDelivery(s.event,s.relays)).successful.length>0?e.succeeded++:e.failed++}catch(t){console.warn(`[sync] Retry failed for ${s.id}:`,t.message),e.failed++}e.purged=await this.client.outboxQueue.purgeOldFailed()}finally{this._processing=!1}return e}async getStats(){const e={running:this.running,interval:this.interval,queue:null};return this.client.outboxQueue&&(e.queue=await this.client.outboxQueue.getStats()),e}}let a=null;class l{constructor(t={}){if(t.relays&&!Array.isArray(t.relays))throw new Error("Relays must be an array");this.relays=t.relays||[],this.privateKey=t.privateKey||this._generatePrivateKey(),this.publicKey=e.getPublicKey(this.privateKey),this.config=t,this._subscriptions=new Map,this._eventCache=new Map,this.persistentStorage=null,this._initReady=this._initialize()}async _initialize(){await(void 0!==globalThis.WebSocket?Promise.resolve():(a||(a=(async()=>{try{const{default:e}=await import("ws");globalThis.WebSocket=e}catch(e){}})()),a)),this.relays.length>0?this.pool=new e.SimplePool({enableReconnect:!1!==this.config.enableReconnect,enablePing:!1!==this.config.enablePing}):this.pool={publish:(e,t)=>[Promise.resolve()],querySync:(e,t,n)=>Promise.resolve([]),subscribeMany:(e,t,n)=>({close:()=>{}}),close:e=>{}},await this._initPersistentStorage()}async _initPersistentStorage(){if(!1!==this.config.persistence&&(this.config.radisk||this.config.appName))try{const e=this.config.appName||"holosphere_default";this.persistentStorage=await async function(e){const t="undefined"!=typeof window&&void 0!==window.indexedDB;if("undefined"!=typeof process&&process.versions,t){const{IndexedDBStorage:t}=await Promise.resolve().then(()=>require("./indexeddb-storage-DLZOgetM.cjs")),n=new t;return await n.init(e),n}{const{MemoryStorage:t}=await Promise.resolve().then(()=>require("./memory-storage-DmePEP2q.cjs")),n=new t;return await n.init(e),n}}(e,{dataDir:this.config.dataDir}),await this._loadFromPersistentStorage(),this.outboxQueue=new i(this.persistentStorage,{maxRetries:this.config.maxRetries||5,baseDelay:this.config.retryBaseDelay||1e3,maxDelay:this.config.retryMaxDelay||6e4,failedTTL:this.config.failedTTL||864e5}),!1!==this.config.backgroundSync&&(this.syncService=new o(this,{interval:this.config.syncInterval||1e4,autoStart:!0}))}catch(e){console.warn("Failed to initialize persistent storage:",e)}}async _loadFromPersistentStorage(){if(this.persistentStorage)try{const e=await this.persistentStorage.getAll("");for(const t of e)t&&t.id&&!t.status&&this._cacheEventSync(t)}catch(e){console.warn("Failed to load from persistent storage:",e)}}async persistentGet(e){if(await this._initReady,!this.persistentStorage)return null;try{return await this.persistentStorage.get(e)||null}catch(t){return console.warn("[nostr] Persistent storage read failed:",t),null}}async persistentGetAll(e){if(await this._initReady,!this.persistentStorage)return[];try{return(await this.persistentStorage.getAll(e)).filter(e=>e&&e.id&&!e.status)}catch(t){return console.warn("[nostr] Persistent storage read failed:",t),[]}}_generatePrivateKey(){const e=new Uint8Array(32);if("undefined"!=typeof window&&window.crypto)window.crypto.getRandomValues(e);else try{const t=globalThis.crypto||global.crypto;if(t&&t.getRandomValues)t.getRandomValues(e);else for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}catch(t){for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}async publish(t,n={}){await this._initReady;const s=n.waitForRelays||!1,r=e.finalizeEvent(t,this.privateKey);if(await this._cacheEvent(r),this.outboxQueue&&await this.outboxQueue.enqueue(r,this.relays),s){return{event:r,results:(await this._attemptDelivery(r,this.relays)).results,queued:!!this.outboxQueue}}return this._attemptDelivery(r,this.relays).catch(e=>{console.warn("[nostr] Immediate delivery failed, queued for retry:",e.message)}),{event:r,results:[],queued:!!this.outboxQueue}}async _attemptDelivery(e,t){const n=await Promise.allSettled(this.pool.publish(t,e)),s=[],r=[],i=[];if(n.forEach((e,n)=>{i.push({relay:t[n],status:e.status,value:e.value,reason:e.reason}),"fulfilled"===e.status?s.push(t[n]):r.push(t[n])}),this.outboxQueue&&await this.outboxQueue.markSent(e.id,s),r.length>0){const s=n.filter(e=>"rejected"===e.status).map(e=>e.reason?.message||e.reason||"unknown").join(", ");console.warn(`[nostr] ${r.length}/${t.length} relays failed for ${e.id.slice(0,8)}: ${s}`)}return{successful:s,failed:r,results:i}}async query(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,s=!1!==t.localFirst;if(0===this.relays.length){return this._getMatchingCachedEvents(e)}if(e["#d"]&&1===e["#d"].length&&e.kinds&&1===e.kinds.length){const t=`d:${e.kinds[0]}:${e["#d"][0]}`,n=this._eventCache.get(t);if(n&&Date.now()-n.timestamp<5e3)return n.events}const r=JSON.stringify(e),i=this._eventCache.get(r);return i&&Date.now()-i.timestamp<5e3?i.events:s&&i?(this._refreshCacheInBackground(e,r,n),i.events):this._queryRelaysAndCache(e,r,n)}async _queryRelaysAndCache(e,t,n){let s=await this.pool.querySync(this.relays,e,{timeout:n});if(e.authors&&e.authors.length>0&&(s=s.filter(t=>e.authors.includes(t.pubkey))),this._eventCache.set(t,{events:s,timestamp:Date.now()}),this._eventCache.size>100){const e=this._eventCache.keys().next().value;this._eventCache.delete(e)}return s}_refreshCacheInBackground(e,t,n){this._queryRelaysAndCache(e,t,n).catch(e=>{console.debug("[nostr] Background cache refresh failed:",e.message)})}refreshPathInBackground(e,t=3e4,n={}){this._doBackgroundPathRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background path refresh failed:",e.message)})}async _doBackgroundPathRefresh(e,t,n){if(0===this.relays.length)return;const s={kinds:[t],authors:n.authors||[this.publicKey],"#d":[e],limit:1},r=n.timeout||3e4,i=(await this.pool.querySync(this.relays,s,{timeout:r})).filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey));i.length>0&&await this._cacheEvent(i[0])}refreshPrefixInBackground(e,t=3e4,n={}){this._doBackgroundPrefixRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background prefix refresh failed:",e.message)})}async _doBackgroundPrefixRefresh(e,t,n){if(0===this.relays.length)return;const s={kinds:[t],authors:n.authors||[this.publicKey],limit:n.limit||1e3},r=n.timeout||3e4;let i=await this.pool.querySync(this.relays,s,{timeout:r});i=i.filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey)),i=i.filter(t=>{const n=t.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(e)});for(const o of i)await this._cacheEvent(o)}async queryHybrid(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,s=this._getMatchingCachedEvents(e);if(0===this.relays.length)return s;let r=[];try{r=await this.pool.querySync(this.relays,e,{timeout:n}),e.authors&&e.authors.length>0&&(r=r.filter(t=>e.authors.includes(t.pubkey)))}catch(l){console.warn("Relay query failed, using local cache only:",l.message)}const i=new Map;for(const c of s){const e=this._getEventKey(c);i.set(e,c)}for(const c of r){const e=this._getEventKey(c),t=i.get(e);c.kind>=3e4&&c.kind<4e4&&t?c.created_at>=t.created_at&&i.set(e,c):i.set(e,c)}const o=Array.from(i.values()),a=JSON.stringify(e);return this._eventCache.set(a,{events:o,timestamp:Date.now()}),o}_getEventKey(e){if(e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1])return`${e.kind}:${t[1]}`}return e.id}async subscribe(e,t,n={}){await this._initReady;const s=`sub-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;if(0===this.relays.length){const r=this._getMatchingCachedEvents(e),i={filter:e,onEvent:t,active:!0};return this._subscriptions.set(s,i),setTimeout(()=>{i.active&&(r.forEach(e=>t(e)),n.onEOSE&&n.onEOSE())},10),{id:s,unsubscribe:()=>{i.active=!1,this._subscriptions.delete(s),i.onEvent=()=>{}}}}const r=this.pool.subscribeMany(this.relays,[e],{onevent:n=>{e.authors&&e.authors.length>0&&!e.authors.includes(n.pubkey)||(this._cacheEvent(n),t(n))},oneose:()=>{n.onEOSE&&n.onEOSE()}});return this._subscriptions.set(s,r),{id:s,unsubscribe:()=>{r.close&&r.close(),this._subscriptions.delete(s)}}}_cacheEventSync(e){const t=e.id;if(this._eventCache.set(t,{events:[e],timestamp:Date.now()}),e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1]){const n=`d:${e.kind}:${t[1]}`,s=this._eventCache.get(n);(!s||!s.events[0]||e.created_at>s.events[0].created_at||e.created_at===s.events[0].created_at&&e.id!==s.events[0].id)&&(this._eventCache.set(n,{events:[e],timestamp:Date.now()}),s&&s.events[0]&&this._eventCache.delete(s.events[0].id),this._invalidateQueryCachesForEvent(e))}}}_invalidateQueryCachesForEvent(e){const t=[];for(const[n,s]of this._eventCache.entries())if(n.startsWith("{"))try{const s=JSON.parse(n);this._eventMatchesFilter(e,s)&&t.push(n)}catch{}for(const n of t)this._eventCache.delete(n)}async _cacheEvent(e){if(this._cacheEventSync(e),this.persistentStorage)try{let t=e.id;if(e.kind>=3e4&&e.kind<4e4){const n=e.tags.find(e=>"d"===e[0]);n&&n[1]&&(t=n[1])}await this.persistentStorage.put(t,e)}catch(t){console.warn("Failed to persist event:",t)}if(0===this.relays.length)for(const n of this._subscriptions.values())n.active&&this._eventMatchesFilter(e,n.filter)&&setTimeout(()=>{n.active&&n.onEvent(e)},10)}_getMatchingCachedEvents(e){const t=[],n=new Map;for(const s of this._eventCache.values())for(const r of s.events||[])if(this._eventMatchesFilter(r,e)){if(r.kind>=3e4&&r.kind<4e4){const e=r.tags.find(e=>"d"===e[0]);if(e&&e[1]){const s=`${r.kind}:${e[1]}`,i=n.get(s);if(!i||r.created_at>i.created_at||r.created_at===i.created_at&&JSON.parse(r.content)?._deleted&&!JSON.parse(i.content)?._deleted){if(i){const e=t.indexOf(i);e>-1&&t.splice(e,1)}n.set(s,r),t.push(r)}continue}}t.push(r)}return t}_eventMatchesFilter(e,t){if(t.kinds&&!t.kinds.includes(e.kind))return!1;if(t.ids&&!t.ids.includes(e.id))return!1;if(t.authors&&!t.authors.includes(e.pubkey))return!1;if(t["#d"]){const n=e.tags.find(e=>"d"===e[0]);if(!n||!t["#d"].includes(n[1]))return!1}return!(t.since&&e.created_at<t.since)&&!(t.until&&e.created_at>t.until)}async getEvent(e){const t=await this.query({ids:[e]});return t.length>0?t[0]:null}clearCache(e=null){if(e)for(const t of this._eventCache.keys())t.includes(e)&&this._eventCache.delete(t);else this._eventCache.clear()}close(){this.syncService&&this.syncService.stop();for(const e of this._subscriptions.values())e.close?e.close():void 0!==e.active&&(e.active=!1);this._subscriptions.clear(),this.pool.close(this.relays),this._eventCache.clear()}getRelayStatus(){return this.relays.map(e=>({url:e,connected:!0}))}}const c={nostr:"./backends/nostr-backend.js",gundb:"./backends/gundb-backend.js",activitypub:"./backends/activitypub-backend.js"},u=new Map;class h{static getAvailableBackends(){return Object.keys(c)}static isAvailable(e){return e in c}static async loadBackend(e){if(u.has(e))return u.get(e);const t=c[e];if(!t)throw new Error(`Unknown backend type: '${e}'. Available backends: ${Object.keys(c).join(", ")}`);try{const s=await import(t),r=s.default||s[`${n=e,n.charAt(0).toUpperCase()+n.slice(1)}Backend`];if(!r)throw new Error(`Backend module '${e}' does not export a valid backend class`);return u.set(e,r),r}catch(s){if("ERR_MODULE_NOT_FOUND"===s.code)throw new Error(`Backend '${e}' requires additional dependencies. Please install them: ${function(e){return{nostr:"npm install nostr-tools",gundb:"npm install gun",activitypub:"npm install express"}[e]||"Check the documentation for required dependencies"}(e)}`);throw s}var n}static async create(e,t){const n=new(await this.loadBackend(e))(t);return await n.init(),n}static register(e,t){"string"==typeof t?c[e]=t:(u.set(e,t),c[e]=null)}}const d="2.0.0-alpha1";function p(e){if("undefined"!=typeof process&&process.env)return process.env[e]}function f(){const e=p("HOLOSPHERE_RELAYS");return e?e.split(",").map(e=>e.trim()).filter(e=>e):["wss://relay.holons.io"]}let m=class{constructor(e={}){if("string"==typeof e&&(e={appName:e}),e&&"object"!=typeof e)throw new TypeError("Config must be an object");if(void 0!==e.appName&&"string"!=typeof e.appName)throw new TypeError("config.appName must be a string");if(void 0!==e.relays&&!Array.isArray(e.relays))throw new TypeError("config.relays must be an array");if(void 0!==e.logLevel&&!["ERROR","WARN","INFO","DEBUG"].includes(e.logLevel))throw new TypeError("config.logLevel must be one of: ERROR, WARN, INFO, DEBUG");if(void 0!==e.backend&&!h.isAvailable(e.backend))throw new TypeError(`config.backend must be one of: ${h.getAvailableBackends().join(", ")}`);this.config={appName:e.appName||p("HOLOSPHERE_APP_NAME")||"holosphere",backend:e.backend||"nostr",relays:e.relays||f(),privateKey:e.privateKey||p("HOLOSPHERE_PRIVATE_KEY"),logLevel:e.logLevel||p("HOLOSPHERE_LOG_LEVEL")||"WARN",hybridMode:!1!==e.hybridMode},this._rawConfig=e,this.logLevels={ERROR:0,WARN:1,INFO:2,DEBUG:3},this.currentLogLevel=this.logLevels[this.config.logLevel]||1,this._backend=null,"nostr"===this.config.backend?this._initNostrSync(e):this._backendReady=this._initBackendAsync(e),this._metrics={writes:0,reads:0,subscriptions:0}}_initNostrSync(e){try{this.client=function(e){return new l(e)}({relays:this.config.relays,privateKey:this.config.privateKey,enableReconnect:!1!==e.enableReconnect,enablePing:!1!==e.enablePing,appName:this.config.appName,radisk:!1!==e.radisk,persistence:!1!==e.persistence,dataDir:e.dataDir}),this._logStartup({version:d,appName:this.config.appName,backend:"nostr",relays:this.config.relays,publicKey:this.client.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,reconnect:!1!==e.enableReconnect,dataDir:e.dataDir}),this._backendReady=Promise.resolve()}catch(t){throw this._log("ERROR","Nostr client initialization failed",{error:t.message}),new Error(`Nostr client initialization failed: ${t.message}`)}}async _initBackendAsync(e){const t=this.config.backend,n=e[t]||{};try{const s={appName:this.config.appName,privateKey:this.config.privateKey,persistence:!1!==e.persistence,dataDir:e.dataDir,...n};this._backend=await h.create(t,s),this.client=this._backend.client||this._backend,this._logStartup({version:d,appName:this.config.appName,backend:t,publicKey:this._backend.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,...this._backend.getStatus()})}catch(s){throw this._log("ERROR",`${t} backend initialization failed`,{error:s.message}),new Error(`${t} backend initialization failed: ${s.message}`)}}async ready(){this._backendReady&&await this._backendReady}get backend(){return this._backend}_log(e,t,n={}){if(this.logLevels[e]<=this.currentLogLevel){const s={timestamp:Date.now(),level:e,message:t,app:this.config.appName,...n};console.log(JSON.stringify(s))}}_logStartup(e){this.currentLogLevel>=this.logLevels.INFO&&(console.log("\n"+"=".repeat(60)),console.log(" HoloSphere - Holonic Geospatial Infrastructure"),console.log("=".repeat(60)),console.log(` Version: ${e.version}`),console.log(` App Name: ${e.appName}`),console.log(` Backend: ${e.backend||"nostr"}`),console.log(" Public Key: "+(e.publicKey?e.publicKey.substring(0,16)+"...":"N/A")),console.log(` Log Level: ${e.logLevel}`),console.log(` Persistence: ${e.persistence?"Enabled":"Disabled"}${e.dataDir?` (${e.dataDir})`:""}`),"nostr"!==e.backend&&e.backend?"gundb"===e.backend?(console.log("\n Gun Peers:"),e.peers&&0!==e.peers.length?e.peers.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")):"activitypub"===e.backend&&(console.log(` Server URL: ${e.serverUrl||"N/A"}`),console.log(` Actor ID: ${e.actorId||"N/A"}`)):(console.log(" Auto-reconnect: "+(e.reconnect?"Enabled":"Disabled")),console.log("\n Connected Relays:"),e.relays&&0!==e.relays.length?e.relays.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")),console.log("=".repeat(60)+"\n"))}metrics(){return{...this._metrics}}};function g(e,n=0){if(!y(e))throw new Error(`Invalid H3 holon ID: ${e}`);const s=[];let r=e;for(let o=t.getResolution(e)-1;o>=n;o--)try{r=t.cellToParent(r,o),s.push(r)}catch(i){break}return s}function y(e){return"string"==typeof e&&(!(e.length<15)&&(!!e.startsWith("8")&&t.isValidCell(e)))}const w=new Map;async function b(e,t,n,s=3e4){const r={kind:s,created_at:Math.floor(Date.now()/1e3),tags:[["d",t]],content:JSON.stringify(n)};return await e.publish(r)}async function _(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=s.authors||[e.publicKey];if(!s.skipPersistent&&e.persistentGet){const o=await e.persistentGet(t);if(o&&o.content)try{const a=JSON.parse(o.content);return a._deleted?null:(s.includeAuthor&&(a._author=o.pubkey),e.refreshPathInBackground&&e.refreshPathInBackground(t,n,{authors:i,timeout:r}),a)}catch(c){console.warn("[nostrGet] Failed to parse persisted event:",c)}}const o={kinds:[n],authors:i,"#d":[t],limit:i.length},a=await e.query(o,{timeout:r});if(0===a.length)return null;const l=a.sort((e,t)=>t.created_at-e.created_at)[0];try{const e=JSON.parse(l.content);return s.includeAuthor&&(e._author=l.pubkey),e}catch(c){return console.error("Failed to parse event content:",c),null}}async function v(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=s.limit||1e3,o=s.authors||[e.publicKey];if(!s.skipPersistent&&e.persistentGetAll){const a=await e.persistentGetAll(t);if(a.length>0){const l=new Map;for(const e of a){if(!e||!e.tags)continue;const n=e.tags.find(e=>"d"===e[0]);if(!n||!n[1]||!n[1].startsWith(t))continue;const r=n[1],i=l.get(r);if(!i||e.created_at>i.created_at)try{const t=JSON.parse(e.content);if(t._deleted)continue;s.includeAuthor&&(t._author=e.pubkey),l.set(r,{data:t,created_at:e.created_at})}catch(u){}}return e.refreshPrefixInBackground&&e.refreshPrefixInBackground(t,n,{authors:o,timeout:r,limit:i}),Array.from(l.values()).map(e=>e.data)}}const a={kinds:[n],authors:o,limit:i},l=(await e.query(a,{timeout:r})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(t)}),c=new Map;for(const h of l){const e=h.tags.find(e=>"d"===e[0])[1],t=c.get(e);if(!t||h.created_at>t.created_at)try{const t=JSON.parse(h.content);if(t._deleted)continue;s.includeAuthor&&(t._author=h.pubkey),c.set(e,{data:t,created_at:h.created_at})}catch(u){console.error("Failed to parse event content:",u)}}return Array.from(c.values()).map(e=>e.data)}async function S(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=s.limit||1e3,o=s.authors||[e.publicKey],a=e.queryHybrid||e.query,l={kinds:[n],authors:o,limit:i},c=(await a.call(e,l,{timeout:r})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(t)}),u=new Map;for(const d of c){const e=d.tags.find(e=>"d"===e[0])[1],t=u.get(e);if(!t||d.created_at>t.created_at)try{const t=JSON.parse(d.content);s.includeAuthor&&(t._author=d.pubkey),u.set(e,{data:t,created_at:d.created_at})}catch(h){console.error("Failed to parse event content:",h)}}return Array.from(u.values()).map(e=>e.data)}async function $(e,t,n=3e4){if(!(await _(e,t,n)))return{reason:"not_found",results:[]};const s={_deleted:!0,_deletedAt:Date.now()},r=await b(e,t,s,n);if(e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(a){}e.clearCache&&e.clearCache(t);const i=`${n}:${e.publicKey}:${t}`,o={kind:5,created_at:Math.floor(Date.now()/1e3),tags:[["a",i]],content:""};try{const n=await e.publish(o);console.log(`✅ NIP-09 deletion event published for ${t}:`,{coordinate:i,relays:n?.relays?.length||0,successful:n?.successful||[]})}catch(l){console.error(`❌ Failed to publish NIP-09 deletion event for ${t}:`,l.message)}return r}async function x(e,t,n=3e4){const s={kinds:[n],authors:[e.publicKey],limit:1e3},r=await e.query(s,{timeout:3e4});let i=[];if(e.persistentStorage)try{i=await e.persistentStorage.getAll(t)}catch(u){}const o=new Map;for(const d of r){const e=d.tags?.find(e=>"d"===e[0]);e&&e[1]&&e[1].startsWith(t)&&o.set(e[1],d)}for(const d of i){const e=d.tags?.find(e=>"d"===e[0]);if(e&&e[1]&&e[1].startsWith(t)){const t=o.get(e[1]);(!t||d.created_at>t.created_at)&&o.set(e[1],d)}}const a=Array.from(o.values());if(0===a.length)return{success:!0,count:0,results:[]};const l=[];for(const d of a){const t=d.tags.find(e=>"d"===e[0])[1];try{const s={_deleted:!0,_deletedAt:Date.now()},r=await b(e,t,s,n);if(l.push(r),e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(u){}e.clearCache&&e.clearCache(t)}catch(h){console.error(`Failed to delete item ${t}:`,h)}}const c=a.map(t=>{const s=t.tags.find(e=>"d"===e[0])[1];return`${n}:${e.publicKey}:${s}`});try{const n={kind:5,created_at:Math.floor(Date.now()/1e3),tags:c.map(e=>["a",e]),content:""},s=await e.publish(n);console.log(`✅ NIP-09 bulk deletion event published for ${t}:`,{itemsDeleted:a.length,coordinates:c.length,relays:s?.relays?.length||0,successful:s?.successful||[]})}catch(h){console.error(`❌ Failed to publish NIP-09 bulk deletion event for ${t}:`,h.message)}return{success:!0,count:a.length,results:l}}function A(e,t,n,s={}){const r=s.kind||3e4;s.includeInitial;const i={kinds:[r],authors:[e.publicKey],"#d":[t],limit:10};return e.subscribe(i,t=>{if(t.pubkey===e.publicKey)try{const e=JSON.parse(t.content);n(e,t)}catch(s){console.error("Failed to parse event in subscription:",s)}else console.warn("[nostrSubscribe] Rejecting event from different author:",{expected:e.publicKey,received:t.pubkey,eventId:t.id})},{onEOSE:()=>{}})}async function O(e,t,n,s={}){const r=s.kind||3e4,i=`${e.publicKey}:${r}:${t}`,o=w.get(i);if(o)return o.callbacks.push(n),{unsubscribe:()=>{const e=o.callbacks.indexOf(n);e>-1&&o.callbacks.splice(e,1),0===o.callbacks.length&&(o.actualSubscription.unsubscribe(),w.delete(i))}};const a=new Set,l=[n];let c=0,u=0,h=Date.now();const d=n=>{if(a.has(n.id))return;if(a.add(n.id),n.pubkey!==e.publicKey){c++;const t=Date.now();return void(t-h>1e4&&(console.warn("[nostrSubscribeMany] ⚠️ Relay not respecting authors filter!",{rejectedCount:c,acceptedCount:u,expected:e.publicKey,message:"Consider using a different relay or implementing private relay"}),h=t))}const s=n.tags.find(e=>"d"===e[0]),r=s?.[1];if(r&&r.startsWith(t)){u++;try{const e=JSON.parse(n.content);for(const t of l)t(e,r,n)}catch(i){console.error("[nostrSubscribeMany] Failed to parse event:",i)}}},p=Math.floor(Date.now()/1e3),f={kinds:[r],authors:[e.publicKey],since:p},m=await e.subscribe(f,d);let g="undefined"!=typeof document&&document.hidden,y=p;const b=async()=>{if("undefined"==typeof document)return;const t=g;if(g=document.hidden,t&&!g){const t=Math.floor(Date.now()/1e3);try{const n={...f,since:y,until:t},s=await e.query(n,{timeout:3e4});for(const e of s)d(e);y=t}catch(n){}}};"undefined"!=typeof document&&document.addEventListener("visibilitychange",b);const _={unsubscribe:()=>{m&&m.unsubscribe&&m.unsubscribe(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",b),w.delete(i)}},v={callbacks:l,actualSubscription:_};return w.set(i,v),_}const N=Object.freeze(Object.defineProperty({__proto__:null,nostrBatchGet:async function(e,t,n=3e4){const s={kinds:[n],"#d":t,limit:t.length},r=await e.query(s),i=new Map;for(const l of r){const e=l.tags.find(e=>"d"===e[0]);if(!e||!e[1])continue;const t=e[1],n=i.get(t);if(!n||l.created_at>n.created_at)try{const e=JSON.parse(l.content);i.set(t,e)}catch(a){console.error("Failed to parse event content:",a)}}const o={};for(const l of t)o[l]=i.get(l)||null;return o},nostrBatchPut:async function(e,t,n=3e4){const s=Object.entries(t).map(([t,s])=>b(e,t,s,n));return Promise.all(s)},nostrDelete:$,nostrDeleteAll:x,nostrGet:_,nostrGetAll:v,nostrGetAllHybrid:S,nostrPut:b,nostrRetry:async function(e,t=3,n=100){let s;for(let i=0;i<=t;i++)try{return await e()}catch(r){if(s=r,i<t){const e=n*Math.pow(2,i);await new Promise(t=>setTimeout(t,e))}}throw s},nostrSubscribe:A,nostrSubscribeMany:O,nostrUpdate:async function(e,t,n,s=3e4){const r=await _(e,t,s);if(!r)throw new Error(`No data found at path: ${t}`);return b(e,t,{...r,...n},s)},nostrWaitFor:async function(e,t,n,s=5e3){return new Promise((r,i)=>{let o,a;const l=()=>{o&&clearTimeout(o),a&&a.unsubscribe()};a=A(e,t,e=>{n(e)&&(l(),r(e))}),o=setTimeout(()=>{l(),i(new Error("Timeout waiting for condition"))},s)})}},Symbol.toStringTag,{value:"Module"}));function k(e,t,n,s=null){const r=R(t),i=R(n);if(s){return`${e}/${r}/${i}/${R(s)}`}return`${e}/${r}/${i}`}function R(e){return encodeURIComponent(e).replace(/%2F/g,"/")}async function I(e,t,n){try{const s=await b(e,t,n);return 0===s.results.length||s.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr write error:",s),s}}async function E(e,t,n={}){const s=await _(e,t,3e4,n);return!s||s._deleted?null:s}async function C(e,t,n={}){const s=n.hybrid&&"function"==typeof e.queryHybrid?S:v;return(await s(e,t,3e4,n)).filter(e=>!(!e||"object"!=typeof e)&&!e._deleted)}async function P(e,t,n){try{const s=await _(e,t);if(!s||!s.id||s._deleted)return!1;const r={...s,...n};r._meta||(r._meta={}),r._meta.timestamp=Date.now();const i=await b(e,t,r);return 0===i.results.length||i.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr update error:",s),s}}async function D(e,t){try{const n=await $(e,t);if("not_found"===n.reason)return!1;return 0===n.results.length||n.results.some(e=>"fulfilled"===e.status)}catch(n){throw console.error("Nostr delete error:",n),n}}async function j(e,t){try{return await x(e,t)}catch(n){throw console.error("Nostr deleteAll error:",n),n}}async function q(e,t,n,s){s.id||(s.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);return I(e,`${t}/${n}/${s.id}`,s)}async function T(e,t,n,s=null){if(s){return E(e,`${t}/${n}/${s}`)}return C(e,`${t}/${n}`)}const J=new n({allErrors:!0,strict:!1}),H=new Map;class F extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.errors=t}}function L(e,t,n,s=!1){const r=function(e,t){const n=t,s=H.get(n);if(s&&Date.now()-s.timestamp<36e5)return s.validator;try{const t=J.compile(e);return H.set(n,{validator:t,timestamp:Date.now()}),t}catch(r){throw new Error(`Schema compilation failed: ${r.message}`)}}(t,n);if(!r(e)){const e=r.errors||[],t=e.map(e=>`${e.instancePath} ${e.message}`).join("; ");if(s)throw new F(`ValidationError: Validation failed: ${t}`,e);return console.warn(`[Schema Validation Warning] ${n}: ${t}`),!1}return!0}function M(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function B(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}const K={number:M,bool:function(e){if("boolean"!=typeof e)throw new Error(`Expected boolean, not ${e}`)},bytes:B,hash:function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");M(e.outputLen),M(e.blockLen)},exists:function(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")},output:function(e,t){B(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}},W=e=>e instanceof Uint8Array,z=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),U=(e,t)=>e<<32-t|e>>>t,V=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];
|
|
2
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!V)throw new Error("Non little-endian hardware is not supported");const G=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Y(e){if(!W(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=G[e[n]];return t}function X(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Q(e){if("string"==typeof e&&(e=X(e)),!W(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class Z{clone(){return this._cloneInto()}}function ee(e){const t=t=>e().update(Q(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}const te=Object.freeze(Object.defineProperty({__proto__:null,Hash:Z,bytesToHex:Y,createView:z,isLE:V,rotr:U,toBytes:Q,utf8ToBytes:X,wrapConstructor:ee},Symbol.toStringTag,{value:"Module"}));class ne extends Z{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=z(this.buffer)}update(e){K.exists(this);const{view:t,buffer:n,blockLen:s}=this,r=(e=Q(e)).length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);if(o===s){const t=z(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){K.exists(this),K.output(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let u=i;u<s;u++)t[u]=0;!function(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),o=Number(n>>r&i),a=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,o,s),e.setUint32(t+c,a,s)}(n,s-8,BigInt(8*this.length),r),this.process(n,0);const o=z(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=a/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)o.setUint32(4*u,c[u],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:i,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=i,s%t&&e.buffer.set(n),e}}const se=(e,t,n)=>e&t^~e&n,re=(e,t,n)=>e&t^e&n^t&n,ie=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ae=new Uint32Array(64);class le extends ne{constructor(){super(64,32,8,!1),this.A=0|oe[0],this.B=0|oe[1],this.C=0|oe[2],this.D=0|oe[3],this.E=0|oe[4],this.F=0|oe[5],this.G=0|oe[6],this.H=0|oe[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:i,G:o,H:a}=this;return[e,t,n,s,r,i,o,a]}set(e,t,n,s,r,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|r,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let u=0;u<16;u++,t+=4)ae[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=ae[u-15],t=ae[u-2],n=U(e,7)^U(e,18)^e>>>3,s=U(t,17)^U(t,19)^t>>>10;ae[u]=s+ae[u-7]+n+ae[u-16]|0}let{A:n,B:s,C:r,D:i,E:o,F:a,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(U(o,6)^U(o,11)^U(o,25))+se(o,a,l)+ie[u]+ae[u]|0,t=(U(n,2)^U(n,13)^U(n,22))+re(n,s,r)|0;c=l,l=a,a=o,o=i+e|0,i=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,s,r,i,o,a,l,c)}roundClean(){ae.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class ce extends le{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const ue=ee(()=>new le);ee(()=>new ce);const he=Object.freeze(Object.defineProperty({__proto__:null,sha256:ue},Symbol.toStringTag,{value:"Module"}));let de=null;async function pe(){if(!de){const e=await Promise.resolve().then(()=>require("./secp256k1-CP0ZkpAx.cjs"));de=e.secp256k1}return de}async function fe(e,t){try{const n=await pe(),s=we(e);return n.sign(s,t).toCompactHex()}catch(n){throw new Error(`Signature generation failed: ${n.message}`)}}function me(e,t){if("string"==typeof e||"string"==typeof t){return("string"==typeof e?e:JSON.stringify(e))===("string"==typeof t?t:JSON.stringify(t))}return("*"===e.holonId||e.holonId===t.holonId)&&(("*"===e.lensName||e.lensName===t.lensName)&&(!e.dataId||"*"===e.dataId||!t.dataId||e.dataId===t.dataId))}async function ge(e,t,n,s={}){const{expiresIn:r=36e5,issuer:i="holosphere",issuerKey:o}=s;if(!Array.isArray(e)||0===e.length)throw new Error("Permissions array cannot be empty");if("object"==typeof t){if(void 0===t.holonId||""===t.holonId)throw new Error('Invalid scope: holonId is required (use "*" for wildcard)');if(void 0===t.lensName||""===t.lensName)throw new Error('Invalid scope: lensName is required (use "*" for wildcard)')}else if("string"==typeof t&&""===t)throw new Error("Invalid scope: cannot be empty string");if(o&&("string"!=typeof o||o.length<32))throw new Error("Invalid issuer key");const a={type:"capability",permissions:e,scope:t,recipient:n,issuer:i,nonce:Date.now().toString(36)+Math.random().toString(36).substring(2,15),issued:Date.now(),expires:Date.now()+r},l=JSON.stringify(a),c=Buffer.from?Buffer.from(l).toString("base64"):btoa(l);if(o){return`${c}.${await fe(l,o)}`}return c}async function ye(e,t,n){try{let s;if("string"==typeof e){const t=e.split(".")[0],n=Buffer.from?Buffer.from(t,"base64").toString("utf8"):atob(t);s=JSON.parse(n)}else s=e;return!(!s||"capability"!==s.type)&&(!(Date.now()>s.expires)&&(!!me(s.scope,n)&&!!s.permissions.includes(t)))}catch(s){return!1}}function we(e){const t="string"==typeof e?e:JSON.stringify(e),n=(new TextEncoder).encode(t);return Y(ue(n))}const be="federations";async function _e(e,t){return await T(e,t,be,e.publicKey)||{id:e.publicKey,federatedWith:[],discoveryEnabled:!1,autoAccept:!1,defaultScope:{holonId:"*",lensName:"*"},defaultPermissions:["read"]}}async function ve(e,t,n){return q(e,t,be,n)}async function Se(e,t,n,s={}){const r=await _e(e,t),i=r.federatedWith.findIndex(e=>e.pubKey===n);if(i>=0){const e=r.federatedWith[i];s.alias&&(e.alias=s.alias),s.inboundCapabilities&&(e.inboundCapabilities=[...e.inboundCapabilities||[],...s.inboundCapabilities]),e.updatedAt=Date.now(),r.federatedWith[i]=e}else r.federatedWith.push({pubKey:n,alias:s.alias||null,addedAt:Date.now(),addedVia:s.addedVia||"manual",inboundCapabilities:s.inboundCapabilities||[],outboundCapabilities:[]});return ve(e,t,r)}async function $e(e,t,n){const s=await _e(e,t),r=s.federatedWith.length;return s.federatedWith=s.federatedWith.filter(e=>e.pubKey!==n),s.federatedWith.length!==r&&ve(e,t,s)}async function xe(e,t){return(await _e(e,t)).federatedWith.map(e=>e.pubKey)}async function Ae(e,t,n,s){const r=(await _e(e,t)).federatedWith.find(e=>e.pubKey===n);return r&&r.inboundCapabilities&&r.inboundCapabilities.find(e=>!(e.expires&&e.expires<Date.now())&&me(e.scope,s))||null}async function Oe(e,t,n,s){const r=await _e(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i)return Se(e,t,n,{addedVia:"capability_received",inboundCapabilities:[s]});i.inboundCapabilities||(i.inboundCapabilities=[]);const o=i.inboundCapabilities.findIndex(e=>JSON.stringify(e.scope)===JSON.stringify(s.scope));return o>=0?i.inboundCapabilities[o]={...s,updatedAt:Date.now()}:i.inboundCapabilities.push({...s,receivedAt:Date.now()}),ve(e,t,r)}async function Ne(e,t,n,s){const r=await _e(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i)throw new Error(`Partner ${n} not found in federation registry`);return i.outboundCapabilities||(i.outboundCapabilities=[]),i.outboundCapabilities.push({tokenHash:s.tokenHash,scope:s.scope,permissions:s.permissions,issuedAt:Date.now(),expires:s.expires}),ve(e,t,r)}async function ke(e,t,n,s,r,i){const o=new Set,a=[];let l=n,c=r,u=i,h=t;for(;o.size<10;){const t=`${h}:${l}:${c}:${u}`;if(o.has(t))return{isCircular:!0,chain:a,reason:"existing_cycle"};if(o.add(t),a.push({holon:l,lens:c,dataId:u}),l===s)return{isCircular:!0,chain:a,reason:"would_create_cycle"};const n=k(h,l,c,u),r=await E(e,n);if(!r)return{isCircular:!1,chain:a};if(!r.hologram||!r.target)return{isCircular:!1,chain:a};h=r.target.appname||h,l=r.target.holonId,c=r.target.lensName||c,u=r.target.dataId||u}return{isCircular:!0,chain:a,reason:"max_depth_exceeded"}}function Re(e,t,n,s,r,i={}){const{authorPubKey:o=null,capability:a=null}=i,l={id:s,hologram:!0,soul:k(r,e,n,s),target:{appname:r,holonId:e,lensName:n,dataId:s},_meta:{created:Date.now(),sourceHolon:e,source:e}};return o&&(l.crossHolosphere=!0,l.target.authorPubKey=o,l._meta.sourcePubKey=o),a&&(l.capability=a,l._meta.grantedAt=Date.now()),l}async function Ie(e,t,n=new Set,s=[],r={}){const{deleteCircular:i=!0,hologramPath:o=null}=r;if(!t||!t.hologram)return t;const{soul:a}=t,l=t.target||{};if(n.has(a)){const r=[...s,a].join(" → ");return console.warn("🔄 Circular reference detected - removing hologram"),console.warn(` Soul: ${a}`),console.warn(` Chain: ${r}`),console.warn(` Source holon: ${l.holonId||"unknown"}`),console.warn(` Lens: ${l.lensName||"unknown"}`),console.warn(` Data ID: ${l.dataId||t.id||"unknown"}`),console.warn(` Resolution depth: ${n.size}`),i&&o&&(console.info(` 🗑️ Deleting circular hologram at: ${o}`),await I(e,o,null)),null}if(n.size>=10){const t=[...s,a].join(" → ");return console.warn("⚠️ Max resolution depth (10) exceeded - removing hologram"),console.warn(` Current soul: ${a}`),console.warn(` Chain: ${t}`),console.warn(` Source holon: ${l.holonId||"unknown"}`),console.warn(` Lens: ${l.lensName||"unknown"}`),i&&o&&(console.info(` 🗑️ Deleting deep chain hologram at: ${o}`),await I(e,o,null)),null}let c;if(n.add(a),s.push(a),t.crossHolosphere&&l.authorPubKey){let n=t.capability;if(!n&&r.appname){const t=await Ae(e,r.appname,l.authorPubKey,{holonId:l.holonId,lensName:l.lensName,dataId:l.dataId});t&&(n=t.token)}if(!n)return console.warn(`❌ Cross-holosphere hologram missing capability: ${a}`),null;if(!(await ye(n,"read",{holonId:l.holonId,lensName:l.lensName,dataId:l.dataId})))return console.warn(`❌ Capability verification failed for cross-holosphere hologram: ${a}`),null;c=await E(e,a,{authors:[l.authorPubKey]})}else c=await E(e,a);return c?c.hologram?Ie(e,c,n,s,{...r,hologramPath:a}):function(e,t){const n=["hologram","soul","target","_meta","id","capability","crossHolosphere"],s={},r=[];for(const a of Object.keys(e))n.includes(a)||(s[a]=e[a],r.push(a));const i=e._meta?.sourceHolon||e._meta?.source||e.target?.holonId,o={...t,...s,_hologram:{isHologram:!0,soul:e.soul,sourceHolon:i,localOverrides:r,crossHolosphere:e.crossHolosphere||!1,sourcePubKey:e._meta?.sourcePubKey||null}};t._meta?o._meta={...t._meta,source:i}:o._meta={source:i};return o}(t,c):null}async function Ee(e,t,n,s,r,i,o="reference"){const a=n.id;if(s===r)return console.info(`⏭️ Skipping propagation - source and target are the same holon: ${s}`),!0;if(!0===n.hologram){if(n.target&&n.target.holonId===r)return console.info("🔄 Skipping propagation - would create circular reference:"),console.info(` Data ID: ${a}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),console.info(` Hologram points to: ${n.target.holonId}`),console.info(` Lens: ${i}`),console.info(` Original soul: ${n.soul||"unknown"}`),!0;if(n.target){const s=k(n.target.appname||t,n.target.holonId,n.target.lensName||i,n.target.dataId||a),o=await E(e,s);if(o?._meta?.activeHolograms){if(o._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${a}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Target holon: ${r}`),!0}}const o=n.target.holonId,l=n.target.dataId||a,c=n.target.lensName||i,u=n.target.appname||t,h=await ke(e,u,o,r,c,l);if(h.isCircular){const e=h.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram copy:"),console.warn(` Data ID: ${a}`),console.warn(` Original source: ${o}`),console.warn(` Would copy to: ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${h.reason}`),!1}const d=k(t,r,i,a),p={...n,_meta:{...n._meta,copiedFrom:s,copiedAt:Date.now()}},f=await I(e,d,p);return f&&n.target&&(await qe(e,n.target.appname||t,n.target.holonId,n.target.lensName||i,n.target.dataId||a,r),console.info(`📋 Copied hologram to ${r}:`),console.info(` Data ID: ${a}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Copied from: ${s}`)),f}if("reference"===o&&n._meta?.activeHolograms){if(n._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${a}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),!0}if("reference"===o){const n=await ke(e,t,s,r,i,a);if(n.isCircular){const e=n.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram creation:"),console.warn(` Data ID: ${a}`),console.warn(` Would create: ${s} → ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${n.reason}`),!1}const o=Re(s,0,i,a,t),l=k(t,r,i,a),c=await I(e,l,o);return c&&await qe(e,t,s,i,a,r),c}return I(e,k(t,r,i,a),{...n,_meta:{...n._meta,source:s}})}async function Ce(e,t,n,s,r,i){const o=k(t,n,s,r),a=await E(e,o);if(!a)return console.warn(`Hologram not found at ${o}`),!1;if(!a.hologram)return console.warn(`Data at ${o} is not a hologram, cannot update overrides`),!1;const l=["hologram","soul","target","_meta","id"],c={};for(const[u,h]of Object.entries(i))l.includes(u)||(c[u]=h);return I(e,o,{...a,...c})}function Pe(e){return e&&!0===e.hologram}function De(e){return e&&e._hologram&&!0===e._hologram.isHologram}function je(e){return De(e)?{soul:e._hologram.soul,sourceHolon:e._hologram.sourceHolon,localOverrides:e._hologram.localOverrides||[]}:null}async function qe(e,t,n,s,r,i){let o=t,a=n,l=s,c=r,u=k(o,a,l,c),h=await E(e,u);if(!h)return console.warn(`Source data not found at ${u}`),!1;let d=0;for(;!0===h.hologram&&h.target&&d<10;)if(d++,o=h.target.appname||o,a=h.target.holonId,l=h.target.lensName||l,c=h.target.dataId||c,u=k(o,a,l,c),h=await E(e,u),!h)return console.warn(`Real source data not found at ${u}`),!1;d>0&&console.info(`📍 Followed hologram chain (depth: ${d}) to real source: ${a}/${l}/${c}`),h._meta||(h._meta={}),Array.isArray(h._meta.activeHolograms)||(h._meta.activeHolograms=[]);const p=Date.now(),f=h._meta.activeHolograms.findIndex(e=>e.targetHolon===i);return f>=0?h._meta.activeHolograms[f].lastUpdated=p:h._meta.activeHolograms.push({targetHolon:i,created:p,lastUpdated:p}),I(e,u,h)}async function Te(e,t,n,s,r,i){let o=t,a=n,l=s,c=r,u=k(o,a,l,c),h=await E(e,u);if(!h)return!1;let d=0;for(;!0===h.hologram&&h.target&&d<10;)if(d++,o=h.target.appname||o,a=h.target.holonId,l=h.target.lensName||l,c=h.target.dataId||c,u=k(o,a,l,c),h=await E(e,u),!h)return!1;if(!h._meta||!Array.isArray(h._meta.activeHolograms))return!1;const p=h._meta.activeHolograms.length;return h._meta.activeHolograms=h._meta.activeHolograms.filter(e=>e.targetHolon!==i),h._meta.activeHolograms.length<p&&I(e,u,h)}async function Je(e,t,n,s,r,i=null){if(!i){const o=k(t,n,s,r);i=await E(e,o)}if(!i||!i._meta||!Array.isArray(i._meta.activeHolograms))return{refreshed:0,holograms:[]};const o=Date.now(),a=[];for(const l of i._meta.activeHolograms){l.lastUpdated=o;const n=k(t,l.targetHolon,s,r),i=await E(e,n);i&&!0===i.hologram&&(i._meta||(i._meta={}),i._meta.lastUpdated=o,await I(e,n,i),a.push({targetHolon:l.targetHolon,dataId:r,timestamp:o}))}return{refreshed:a.length,holograms:a,sourceData:i}}async function He(e,t,n,s,r,i={}){const{deleteData:o=!0}=i,a=k(t,n,s,r),l={success:!1,wasHologram:!1,sourceHolon:null,activeHologramsUpdated:!1,error:null};try{const i=await E(e,a);if(!i)return console.warn(`🗑️ Hologram not found at ${a}`),l.error="Hologram not found",l;if(!0===i.hologram&&i.target){l.wasHologram=!0,l.sourceHolon=i.target.holonId,console.info("🗑️ Deleting hologram:"),console.info(` Path: ${a}`),console.info(` Data ID: ${r}`),console.info(` From holon: ${n}`),console.info(` Source holon: ${i.target.holonId}`),console.info(` Lens: ${s}`);const o=await Te(e,i.target.appname||t,i.target.holonId,i.target.lensName||s,i.target.dataId||r,n);l.activeHologramsUpdated=o,o?console.info(" ✓ Removed from activeHolograms on source"):console.warn(" ⚠️ Could not update activeHolograms on source (may already be removed)")}else console.info(`🗑️ Deleting non-hologram data at ${a}`);if(o){const t=await I(e,a,null);l.success=t,t?console.info(" ✓ Hologram deleted successfully"):(console.warn(" ⚠️ Failed to delete hologram data"),l.error="Failed to delete hologram data")}else l.success=!0;return l}catch(c){return console.error(`❌ Error deleting hologram at ${a}:`,c),l.error=c.message||"Unknown error",l}}async function Fe(e,t,n,s,r={}){const{dryRun:i=!1}=r,o={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${i?"[DRY RUN] ":""}Cleaning up circular holograms in ${n}/${s}...`);try{k(t,n,s);const r=k(t,n,s,"_index"),a=await E(e,r);if(!a||!Array.isArray(a.items))return console.warn(` No index found for ${n}/${s}, cannot scan for circular references`),console.info(" Tip: Provide specific IDs to check using cleanupCircularHologramsByIds()"),o;for(const l of a.items){o.scanned++;const r=k(t,n,s,l),a=await E(e,r);if(!a||!0!==a.hologram||!a.target)continue;const c=a.target.holonId,u=a.target.dataId||l,h=a.target.lensName||s,d=k(a.target.appname||t,c,h,u),p=await E(e,d);if(p&&!0===p.hologram&&p.target&&p.target.holonId===n){o.circularFound++;const a={itemId:l,path:r,pointsTo:`${c}/${h}/${u}`,circularWith:`${p.target.holonId}/${p.target.lensName}/${p.target.dataId}`};if(o.details.push(a),console.warn(" 🔄 Found circular hologram:"),console.warn(` ${n}/${s}/${l} → ${c}/${h}/${u} → ${n}`),!i){const r=await He(e,t,n,s,l);r.success?(o.deleted++,console.info(" ✓ Deleted circular hologram")):(o.errors.push({itemId:l,error:r.error}),console.error(` ❌ Failed to delete: ${r.error}`))}}}return console.info(`🧹 Cleanup complete for ${n}/${s}:`),console.info(` Scanned: ${o.scanned}`),console.info(` Circular found: ${o.circularFound}`),console.info(` Deleted: ${o.deleted}`),o.errors.length>0&&console.warn(` Errors: ${o.errors.length}`),o}catch(a){return console.error("❌ Error during cleanup:",a),o.errors.push({error:a.message}),o}}async function Le(e,t,n,s,r,i={}){const{dryRun:o=!1}=i,a={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${o?"[DRY RUN] ":""}Cleaning up circular holograms for ${r.length} IDs in ${n}/${s}...`);for(const l of r){a.scanned++;const r=k(t,n,s,l),i=await E(e,r);if(!i||!0!==i.hologram||!i.target)continue;const c=i.target.holonId,u=i.target.dataId||l,h=i.target.lensName||s,d=k(i.target.appname||t,c,h,u),p=await E(e,d);if(p&&!0===p.hologram&&p.target&&p.target.holonId===n){a.circularFound++;const i={itemId:l,path:r,pointsTo:`${c}/${h}/${u}`,circularWith:`${p.target.holonId}/${p.target.lensName}/${p.target.dataId}`};if(a.details.push(i),console.warn(` 🔄 Found circular hologram: ${l}`),console.warn(` Chain: ${n} → ${c} → ${n}`),!o){const r=await He(e,t,n,s,l);r.success?(a.deleted++,console.info(" ✓ Deleted")):(a.errors.push({itemId:l,error:r.error}),console.error(` ❌ Failed: ${r.error}`))}}}return console.info(`🧹 Cleanup complete: scanned=${a.scanned}, circular=${a.circularFound}, deleted=${a.deleted}`),a}async function Me(e,t,n,s={}){const{throttle:r=0,filter:i=null,includeFederated:o=!1,triggerInitial:a=!1,realtimeOnly:l=!0,resolveHolograms:c=!0}=s;let u=0,h=null;const d=new Set;let p=!0;const f=await async function(e,t,n,s={}){return t.split("/").length<=3?await O(e,t+"/",(e,t)=>{const s=t.split("/").pop();n(e,s)},s):A(e,t,e=>{n(e,t.split("/").pop())},s)}(e,t,async(t,s)=>{if(!p)return;const o=`${s}-${t?.id||""}-${t?._meta?.timestamp||Date.now()}`;if(d.has(o))return;d.add(o);let a=t;if(c&&t&&!0===t.hologram)try{if(a=await Ie(e,t),!a)return}catch(f){return void console.warn("Failed to resolve hologram in subscription:",f)}if(i&&!i(a,s))return;const l=Date.now();if(r>0&&l-u<r)return h&&clearTimeout(h),void(h=setTimeout(()=>{u=Date.now(),n(a,s)},r-(l-u)));u=l,n(a,s)},{});return{path:t,unsubscribe:()=>{p=!1,h&&clearTimeout(h),f&&f.unsubscribe&&f.unsubscribe(),d.clear()}}}class Be{constructor(){this.subscriptions=new Map}register(e,t){this.subscriptions.set(e,t)}unregister(e){const t=this.subscriptions.get(e);t&&(t.unsubscribe(),this.subscriptions.delete(e))}unsubscribeAll(){for(const[e,t]of this.subscriptions)t.unsubscribe();this.subscriptions.clear()}count(){return this.subscriptions.size}}async function Ke(e,t,n,s,r,i={}){const{maxLevel:o=3,operation:a="summarize"}=i;if(!y(n))throw new Error("Upcast only supported for geographic (H3) holons, not noospheric holons");const l=g(n).slice(0,o);if(0===l.length)return!0;const c=l.map(async i=>async function(e,t,n,s,r,i,o){const a=Re(n,0,r,i,t);a._meta.operation=o,a._meta.upcast=!0;const l=`${t}/${s}/${r}/${i}`;return I(e,l,a)}(e,t,n,i,s,r,a));return await Promise.all(c),!0}const We=30078,ze=30079,Ue=30080;async function Ve(e,t,n,s={}){const{scope:r={holonId:"*",lensName:"*"},permissions:i=["read"],message:o="Federation request",expiresIn:a=2592e6}=s,l=await ge(i,r,n,{issuerKey:e.privateKey,expiresIn:a}),c={kind:We,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-request-${n.slice(0,16)}`],["p",n],["holosphere",t],["scope",JSON.stringify(r)],["permissions",i.join(",")]],content:JSON.stringify({message:o,offeredCapability:l,requestedScope:r,requestedPermissions:i})},u=await e.publish(c);return{eventId:u.id||null,targetPubKey:n,scope:r,permissions:i,offeredCapability:l,...u}}async function Ge(e,t){const n={kinds:[We],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content),s=e.tags.find(e=>"scope"===e[0]),r=e.tags.find(e=>"permissions"===e[0]),i=e.tags.find(e=>"holosphere"===e[0]),o={eventId:e.id,requesterPubKey:e.pubkey,appname:i?.[1],scope:s?JSON.parse(s[1]):{holonId:"*",lensName:"*"},permissions:r?r[1].split(","):["read"],message:n.message,offeredCapability:n.offeredCapability,timestamp:e.created_at};t(o)}catch(n){console.error("Failed to parse federation request:",n)}})}async function Ye(e,t,n,s={}){const{scope:r=n.scope,permissions:i=n.permissions,alias:o=null,expiresIn:a=2592e6}=s,l=await ge(i,r,n.requesterPubKey,{issuerKey:e.privateKey,expiresIn:a});await Se(e,t,n.requesterPubKey,{alias:o,addedVia:"nostr_discovery",inboundCapabilities:[{token:n.offeredCapability,scope:n.scope,permissions:n.permissions,expires:Date.now()+a}]});const c={kind:ze,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-accept-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t],["scope",JSON.stringify(r)],["permissions",i.join(",")]],content:JSON.stringify({acceptedScope:r,grantedCapability:l})},u=await e.publish(c);return{eventId:u.id||null,requesterPubKey:n.requesterPubKey,grantedCapability:l,acceptedScope:r,...u}}async function Xe(e,t,n,s=""){const r={kind:Ue,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-decline-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t]],content:JSON.stringify({reason:s})},i=await e.publish(r);return{eventId:i.id||null,requesterPubKey:n.requesterPubKey,reason:s,...i}}async function Qe(e,t,n){const s={kinds:[ze],"#p":[e.publicKey]};return e.subscribe(s,async s=>{try{const r=JSON.parse(s.content),i=s.tags.find(e=>"scope"===e[0]),o=s.tags.find(e=>"permissions"===e[0]);await Oe(e,t,s.pubkey,{token:r.grantedCapability,scope:i?JSON.parse(i[1]):r.acceptedScope,permissions:o?o[1].split(","):["read"],expires:Date.now()+2592e6}),n({accepterPubKey:s.pubkey,originalRequestId:s.tags.find(e=>"e"===e[0])?.[1],acceptedScope:r.acceptedScope,grantedCapability:r.grantedCapability,timestamp:s.created_at})}catch(r){console.error("Failed to parse federation acceptance:",r)}})}async function Ze(e,t){const n={kinds:[Ue],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content);t({declinerPubKey:e.pubkey,originalRequestId:e.tags.find(e=>"e"===e[0])?.[1],reason:n.reason||"",timestamp:e.created_at})}catch(n){console.error("Failed to parse federation decline:",n)}})}async function et(e,t={}){const n=t.since||Math.floor((Date.now()-2592e6)/1e3),s={kinds:[We],authors:[e.publicKey],since:n},r=await e.query(s),i={kinds:[ze,Ue],"#p":[e.publicKey],since:n},o=await e.query(i),a=new Set;for(const u of o){const e=u.tags.find(e=>"e"===e[0]);e&&a.add(e[1])}const l=[];for(const u of r)if(!a.has(u.id))try{const e=JSON.parse(u.content),t=u.tags.find(e=>"p"===e[0]),n=u.tags.find(e=>"scope"===e[0]),s=u.tags.find(e=>"permissions"===e[0]);l.push({eventId:u.id,targetPubKey:t?.[1],scope:n?JSON.parse(n[1]):{holonId:"*",lensName:"*"},permissions:s?s[1].split(","):["read"],message:e.message,timestamp:u.created_at})}catch(c){console.error("Failed to parse pending request:",c)}return l}const tt="RFC3986",nt={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},st=Array.isArray,rt=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),it=1024;function ot(e,t){if(st(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const at=Object.prototype.hasOwnProperty,lt={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ct=Array.isArray,ut=Array.prototype.push,ht=function(e,t){ut.apply(e,ct(t)?t:[t])},dt=Date.prototype.toISOString,pt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,r)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===n)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let o="";for(let a=0;a<i.length;a+=it){const e=i.length>=it?i.slice(a,a+it):i,t=[];for(let n=0;n<e.length;++n){let s=e.charCodeAt(n);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?t[t.length]=e.charAt(n):s<128?t[t.length]=rt[s]:s<2048?t[t.length]=rt[192|s>>6]+rt[128|63&s]:s<55296||s>=57344?t[t.length]=rt[224|s>>12]+rt[128|s>>6&63]+rt[128|63&s]:(n+=1,s=65536+((1023&s)<<10|1023&e.charCodeAt(n)),t[t.length]=rt[240|s>>18]+rt[128|s>>12&63]+rt[128|s>>6&63]+rt[128|63&s])}o+=t.join("")}return o},encodeValuesOnly:!1,format:tt,formatter:nt[tt],indices:!1,serializeDate:e=>dt.call(e),skipNulls:!1,strictNullHandling:!1};const ft={};function mt(e,t,n,s,r,i,o,a,l,c,u,h,d,p,f,m,g,y){let w=e,b=y,_=0,v=!1;for(;void 0!==(b=b.get(ft))&&!v;){const t=b.get(e);if(_+=1,void 0!==t){if(t===_)throw new RangeError("Cyclic object value");v=!0}void 0===b.get(ft)&&(_=0)}if("function"==typeof c?w=c(t,w):w instanceof Date?w=d?.(w):"comma"===n&&ct(w)&&(w=ot(w,function(e){return e instanceof Date?d?.(e):e})),null===w){if(i)return l&&!m?l(t,pt.encoder,g,"key",p):t;w=""}if("string"==typeof(S=w)||"number"==typeof S||"boolean"==typeof S||"symbol"==typeof S||"bigint"==typeof S||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(w)){if(l){const e=m?t:l(t,pt.encoder,g,"key",p);return[f?.(e)+"="+f?.(l(w,pt.encoder,g,"value",p))]}return[f?.(t)+"="+f?.(String(w))]}var S;const $=[];if(void 0===w)return $;let x;if("comma"===n&&ct(w))m&&l&&(w=ot(w,l)),x=[{value:w.length>0?w.join(",")||null:void 0}];else if(ct(c))x=c;else{const e=Object.keys(w);x=u?e.sort(u):e}const A=a?String(t).replace(/\./g,"%2E"):String(t),O=s&&ct(w)&&1===w.length?A+"[]":A;if(r&&ct(w)&&0===w.length)return O+"[]";for(let N=0;N<x.length;++N){const t=x[N],b="object"==typeof t&&void 0!==t.value?t.value:w[t];if(o&&null===b)continue;const v=h&&a?t.replace(/\./g,"%2E"):t,S=ct(w)?"function"==typeof n?n(O,v):O:O+(h?"."+v:"["+v+"]");y.set(e,_);const A=new WeakMap;A.set(ft,y),ht($,mt(b,S,n,s,r,i,o,a,"comma"===n&&m&&ct(w)?null:l,c,u,h,d,p,f,m,g,A))}return $}function gt(e,t={}){let n=e;const s=function(e=pt){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||pt.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=tt;if(void 0!==e.format){if(!at.call(nt,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=nt[n];let r,i=pt.filter;if(("function"==typeof e.filter||ct(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in lt?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":pt.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=void 0===e.allowDots?1==!!e.encodeDotInKeys||pt.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:pt.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:pt.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:pt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?pt.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:pt.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:pt.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:pt.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:pt.encodeValuesOnly,filter:i,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:pt.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:pt.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:pt.strictNullHandling}}(t);let r,i;"function"==typeof s.filter?(i=s.filter,n=i("",n)):ct(s.filter)&&(i=s.filter,r=i);const o=[];if("object"!=typeof n||null===n)return"";const a=lt[s.arrayFormat],l="comma"===a&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let d=0;d<r.length;++d){const e=r[d];s.skipNulls&&null===n[e]||ht(o,mt(n[e],e,a,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,c))}const u=o.join(s.delimiter);let h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}const yt="4.104.0";let wt,bt,_t,vt,St,$t,xt,At,Ot,Nt=!1;class kt{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const Rt=()=>{wt||function(e,t={auto:!1}){if(Nt)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(wt)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${wt}'\``);Nt=t.auto,wt=e.kind,bt=e.fetch,_t=e.FormData,vt=e.File,St=e.ReadableStream,$t=e.getMultipartRequestOptions,xt=e.getDefaultAgent,At=e.fileFromPath,Ot=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let n,s,r,i;try{n=fetch,s=Request,r=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${t}`)}return{kind:"web",fetch:n,Request:s,Response:r,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new kt(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0})};Rt();class It extends Error{}class Et extends It{constructor(e,t,n,s){super(`${Et.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Pt({message:n,cause:En(t)});const r=t?.error;return 400===e?new jt(e,r,n,s):401===e?new qt(e,r,n,s):403===e?new Tt(e,r,n,s):404===e?new Jt(e,r,n,s):409===e?new Ht(e,r,n,s):422===e?new Ft(e,r,n,s):429===e?new Lt(e,r,n,s):e>=500?new Mt(e,r,n,s):new Et(e,r,n,s)}}class Ct extends Et{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Pt extends Et{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Dt extends Pt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class jt extends Et{}class qt extends Et{}class Tt extends Et{}class Jt extends Et{}class Ht extends Et{}class Ft extends Et{}class Lt extends Et{}class Mt extends Et{}class Bt extends It{constructor(){super("Could not parse response content as the length limit was reached")}}class Kt extends It{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var Wt,zt=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Ut=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Vt{constructor(){Wt.set(this,void 0),this.buffer=new Uint8Array,zt(this,Wt,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let r;for(;null!=(r=Gt(this.buffer,Ut(this,Wt,"f")));){if(r.carriage&&null==Ut(this,Wt,"f")){zt(this,Wt,r.index,"f");continue}if(null!=Ut(this,Wt,"f")&&(r.index!==Ut(this,Wt,"f")+1||r.carriage)){s.push(this.decodeText(this.buffer.slice(0,Ut(this,Wt,"f")-1))),this.buffer=this.buffer.slice(Ut(this,Wt,"f")),zt(this,Wt,null,"f");continue}const e=null!==Ut(this,Wt,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));s.push(t),this.buffer=this.buffer.slice(r.index),zt(this,Wt,null,"f")}return s}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new It(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new It(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new It("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function Gt(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function Yt(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function Xt(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}Wt=new WeakMap,Vt.NEWLINE_CHARS=new Set(["\n","\r"]),Vt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Qt{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new Qt(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new It("Attempted to iterate over a response with no body");const n=new Zt,s=new Vt,r=Xt(e.body);for await(const i of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=Yt(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const e of s.decode(i)){const t=n.decode(e);t&&(yield t)}for(const i of s.flush()){const e=n.decode(i);e&&(yield e)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event||n.event.startsWith("response.")||n.event.startsWith("transcript.")){let t;try{t=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if(t&&t.error)throw new Et(void 0,t.error,void 0,wn(e.headers));yield t}else{let e;try{e=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if("error"==n.event)throw new Et(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}static fromReadableStream(e,t){let n=!1;return new Qt(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new Vt,n=Xt(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new Qt(()=>s(e),this.controller),new Qt(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new St({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const i=n.encode(JSON.stringify(s)+"\n");e.enqueue(i)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}class Zt{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}const en=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,tn=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&nn(e),nn=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function sn(e,t,n){if(e=await e,tn(e))return e;if(en(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=nn(s)?[await s.arrayBuffer()]:[s];return new vt(r,t,n)}const s=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(await e.arrayBuffer());else{if(!on(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`);for await(const n of e)t.push(n)}return t}(e);if(t||(t=function(e){return rn(e.name)||rn(e.filename)||rn(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new vt(s,t,n)}const rn=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,on=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],an=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],ln=async e=>{const t=await cn(e.body);return $t(t,e)},cn=async e=>{const t=new _t;return await Promise.all(Object.entries(e||{}).map(([e,n])=>un(t,e,n))),t},un=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if((e=>tn(e)||en(e)||Ot(e))(n)){const s=await sn(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map(n=>un(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,s])=>un(e,`${t}[${n}]`,s)))}}};var hn;async function dn(e){const{response:t}=e;if(e.options.stream)return Tn("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Qt.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const e=await t.json();return Tn("response",t.status,t.url,t.headers,e),pn(e,t)}const r=await t.text();return Tn("response",t.status,t.url,t.headers,r),r}function pn(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}Rt();class fn extends Promise{constructor(e,t=dn){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new fn(this.responsePromise,async t=>pn(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class mn{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=In("maxRetries",t),this.timeout=In("timeout",n),this.httpAgent=s,this.fetch=r??bt}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...An(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Jn()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async n=>{const s=n&&nn(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:r,query:i,headers:o={}}=n,a=ArrayBuffer.isView(n.body)||n.__binaryRequest&&"string"==typeof n.body?n.body:an(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,l=this.calculateContentLength(a),c=this.buildURL(r,i);"timeout"in n&&In("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const u=n.httpAgent??this.httpAgent??xt(c),h=n.timeout+1e3;"number"==typeof u?.options?.timeout&&h>(u.options.timeout??0)&&(u.options.timeout=h),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:s,...a&&{body:a},headers:this.buildHeaders({options:n,headers:o,contentLength:l,retryCount:t}),...u&&{agent:u},signal:n.signal??null},url:c,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const i=this.defaultHeaders(e);return jn(r,i),jn(r,t),an(e.body)&&"node"!==wt&&delete r["content-type"],void 0===Hn(i,"x-stainless-retry-count")&&void 0===Hn(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),void 0===Hn(i,"x-stainless-timeout")&&void 0===Hn(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,n,s){return Et.generate(e,t,n,s)}request(e,t=null){return new fn(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:i,timeout:o}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:i,options:n}),Tn("request",i,n,r.headers),n.signal?.aborted)throw new Ct;const a=new AbortController,l=await this.fetchWithTimeout(i,r,o,a).catch(En);if(l instanceof Error){if(n.signal?.aborted)throw new Ct;if(t)return this.retryRequest(n,t);if("AbortError"===l.name)throw new Dt;throw new Pt({cause:l})}const c=wn(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Tn(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,i,c),this.retryRequest(n,t,c)}const e=await l.text().catch(e=>En(e).message),s=On(e),r=s?void 0:e;Tn(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,c,r);throw this.makeStatusError(l.status,s,r,c)}return{response:l,options:n,controller:a}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new yn(this,n,e)}buildURL(e,t){const n=kn(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Pn(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new It(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:r,...i}=t||{};r&&r.addEventListener("abort",()=>s.abort());const o=setTimeout(()=>s.abort(),n),a={signal:s.signal,...i};return a.method&&(a.method=a.method.toUpperCase()),this.fetch.call(void 0,e,a).finally(()=>{clearTimeout(o)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const i=n?.["retry-after"];if(i&&!s){const e=parseFloat(i);s=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Rn(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${yt}`}}class gn{constructor(e,t,n,s){hn.set(this,void 0),function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===s?r.call(e,n):r?r.value=n:t.set(e,n)}(this,hn,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new It("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)}(this,hn,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(hn=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class yn extends fn{constructor(e,t,n){super(t,async t=>new n(e,t.response,await dn(t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const wn=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),bn={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},_n=e=>"object"==typeof e&&null!==e&&!Pn(e)&&Object.keys(e).every(e=>Dn(bn,e)),vn=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":$n(Deno.build.os),"X-Stainless-Arch":Sn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":$n(process.platform),"X-Stainless-Arch":Sn(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Sn=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",$n=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let xn;const An=()=>xn??(xn=vn()),On=e=>{try{return JSON.parse(e)}catch(t){return}},Nn=/^[a-z][a-z0-9+.-]*:/i,kn=e=>Nn.test(e),Rn=e=>new Promise(t=>setTimeout(t,e)),In=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new It(`${e} must be an integer`);if(t<0)throw new It(`${e} must be a positive integer`);return t},En=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Cn=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Pn(e){if(!e)return!0;for(const t in e)return!1;return!0}function Dn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function jn(e,t){for(const n in t){if(!Dn(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}const qn=new Set(["authorization","api-key"]);function Tn(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const n=t.map(e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const n in e.headers)qn.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)qn.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e});console.log(`OpenAI:DEBUG:${e}`,...n)}}const Jn=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),Hn=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,n)=>t+n.toUpperCase());for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function Fn(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Ln extends gn{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Mn extends gn{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class Bn{constructor(e){this._client=e}}let Kn=class extends Bn{list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Un,{query:t,...n})}},Wn=class extends Bn{constructor(){super(...arguments),this.messages=new Kn(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/chat/completions",zn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class zn extends Mn{}class Un extends Mn{}Wn.ChatCompletionsPage=zn,Wn.Messages=Kn;let Vn=class extends Bn{constructor(){super(...arguments),this.completions=new Wn(this._client)}};Vn.Completions=Wn,Vn.ChatCompletionsPage=zn;class Gn extends Bn{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Yn extends Bn{create(e,t){return this._client.post("/audio/transcriptions",ln({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Xn extends Bn{create(e,t){return this._client.post("/audio/translations",ln({body:e,...t,__metadata:{model:e.model}}))}}class Qn extends Bn{constructor(){super(...arguments),this.transcriptions=new Yn(this._client),this.translations=new Xn(this._client),this.speech=new Gn(this._client)}}Qn.Transcriptions=Yn,Qn.Translations=Xn,Qn.Speech=Gn;class Zn extends Bn{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/batches",es,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class es extends Mn{}Zn.BatchesPage=es;var ts,ns,ss,rs,is,os,as,ls,cs,us,hs,ds,ps,fs=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},ms=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class gs{constructor(){ts.add(this),this.controller=new AbortController,ns.set(this,void 0),ss.set(this,()=>{}),rs.set(this,()=>{}),is.set(this,void 0),os.set(this,()=>{}),as.set(this,()=>{}),ls.set(this,{}),cs.set(this,!1),us.set(this,!1),hs.set(this,!1),ds.set(this,!1),fs(this,ns,new Promise((e,t)=>{fs(this,ss,e,"f"),fs(this,rs,t,"f")}),"f"),fs(this,is,new Promise((e,t)=>{fs(this,os,e,"f"),fs(this,as,t,"f")}),"f"),ms(this,ns,"f").catch(()=>{}),ms(this,is,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ms(this,ts,"m",ps).bind(this))},0)}_connected(){this.ended||(ms(this,ss,"f").call(this),this._emit("connect"))}get ended(){return ms(this,cs,"f")}get errored(){return ms(this,us,"f")}get aborted(){return ms(this,hs,"f")}abort(){this.controller.abort()}on(e,t){return(ms(this,ls,"f")[e]||(ms(this,ls,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=ms(this,ls,"f")[e];if(!n)return this;const s=n.findIndex(e=>e.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(ms(this,ls,"f")[e]||(ms(this,ls,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{fs(this,ds,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){fs(this,ds,!0,"f"),await ms(this,is,"f")}_emit(e,...t){if(ms(this,cs,"f"))return;"end"===e&&(fs(this,cs,!0,"f"),ms(this,os,"f").call(this));const n=ms(this,ls,"f")[e];if(n&&(ms(this,ls,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return ms(this,ds,"f")||n?.length||Promise.reject(e),ms(this,rs,"f").call(this,e),ms(this,as,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];ms(this,ds,"f")||n?.length||Promise.reject(e),ms(this,rs,"f").call(this,e),ms(this,as,"f").call(this,e),this._emit("end")}}_emitFinal(){}}ns=new WeakMap,ss=new WeakMap,rs=new WeakMap,is=new WeakMap,os=new WeakMap,as=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,hs=new WeakMap,ds=new WeakMap,ts=new WeakSet,ps=function(e){if(fs(this,us,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new Ct),e instanceof Ct)return fs(this,hs,!0,"f"),this._emit("abort",e);if(e instanceof It)return this._emit("error",e);if(e instanceof Error){const t=new It(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new It(String(e)))};var ys,ws,bs,_s,vs,Ss,$s,xs,As,Os,Ns,ks,Rs,Is,Es,Cs,Ps,Ds,js,qs,Ts,Js,Hs=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},Fs=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n};class Ls extends gs{constructor(){super(...arguments),ys.add(this),ws.set(this,[]),bs.set(this,{}),_s.set(this,{}),vs.set(this,void 0),Ss.set(this,void 0),$s.set(this,void 0),xs.set(this,void 0),As.set(this,void 0),Os.set(this,void 0),Ns.set(this,void 0),ks.set(this,void 0),Rs.set(this,void 0)}[(ws=new WeakMap,bs=new WeakMap,_s=new WeakMap,vs=new WeakMap,Ss=new WeakMap,$s=new WeakMap,xs=new WeakMap,As=new WeakMap,Os=new WeakMap,Ns=new WeakMap,ks=new WeakMap,Rs=new WeakMap,ys=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Ls;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Qt.fromReadableStream(e,this.controller);for await(const r of s)Hs(this,ys,"m",Is).call(this,r);if(s.controller.signal?.aborted)throw new Ct;return this._addRun(Hs(this,ys,"m",Es).call(this))}toReadableStream(){return new Qt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const i=new Ls;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...s,stream:!0},a=await e.submitToolOutputs(t,n,o,{...r,signal:this.controller.signal});this._connected();for await(const l of a)Hs(this,ys,"m",Is).call(this,l);if(a.controller.signal?.aborted)throw new Ct;return this._addRun(Hs(this,ys,"m",Es).call(this))}static createThreadAssistantStream(e,t,n){const s=new Ls;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const r=new Ls;return r._run(()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return Hs(this,Ns,"f")}currentRun(){return Hs(this,ks,"f")}currentMessageSnapshot(){return Hs(this,vs,"f")}currentRunStepSnapshot(){return Hs(this,Rs,"f")}async finalRunSteps(){return await this.done(),Object.values(Hs(this,bs,"f"))}async finalMessages(){return await this.done(),Object.values(Hs(this,_s,"f"))}async finalRun(){if(await this.done(),!Hs(this,Ss,"f"))throw Error("Final run was not received.");return Hs(this,Ss,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const o of i)Hs(this,ys,"m",Is).call(this,o);if(i.controller.signal?.aborted)throw new Ct;return this._addRun(Hs(this,ys,"m",Es).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const a of o)Hs(this,ys,"m",Is).call(this,a);if(o.controller.signal?.aborted)throw new Ct;return this._addRun(Hs(this,ys,"m",Es).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!Fn(t)||!Fn(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...s);continue}for(const e of s){if(!Fn(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}Is=function(e){if(!this.ended)switch(Fs(this,Ns,e,"f"),Hs(this,ys,"m",Ds).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Hs(this,ys,"m",Js).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Hs(this,ys,"m",Ps).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Hs(this,ys,"m",Cs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Es=function(){if(this.ended)throw new It("stream has ended, this shouldn't happen");if(!Hs(this,Ss,"f"))throw Error("Final run has not been received");return Hs(this,Ss,"f")},Cs=function(e){const[t,n]=Hs(this,ys,"m",qs).call(this,e,Hs(this,vs,"f"));Fs(this,vs,t,"f"),Hs(this,_s,"f")[t.id]=t;for(const s of n){const e=t.content[s.index];"text"==e?.type&&this._emit("textCreated",e.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=Hs(this,$s,"f")){if(Hs(this,xs,"f"))switch(Hs(this,xs,"f").type){case"text":this._emit("textDone",Hs(this,xs,"f").text,Hs(this,vs,"f"));break;case"image_file":this._emit("imageFileDone",Hs(this,xs,"f").image_file,Hs(this,vs,"f"))}Fs(this,$s,n.index,"f")}Fs(this,xs,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Hs(this,$s,"f")){const t=e.data.content[Hs(this,$s,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Hs(this,vs,"f"));break;case"text":this._emit("textDone",t.text,Hs(this,vs,"f"))}}Hs(this,vs,"f")&&this._emit("messageDone",e.data),Fs(this,vs,void 0,"f")}},Ps=function(e){const t=Hs(this,ys,"m",js).call(this,e);switch(Fs(this,Rs,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==Hs(this,As,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Hs(this,Os,"f")&&this._emit("toolCallDone",Hs(this,Os,"f")),Fs(this,As,e.index,"f"),Fs(this,Os,t.step_details.tool_calls[e.index],"f"),Hs(this,Os,"f")&&this._emit("toolCallCreated",Hs(this,Os,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Fs(this,Rs,void 0,"f");"tool_calls"==e.data.step_details.type&&Hs(this,Os,"f")&&(this._emit("toolCallDone",Hs(this,Os,"f")),Fs(this,Os,void 0,"f")),this._emit("runStepDone",e.data,t)}},Ds=function(e){Hs(this,ws,"f").push(e),this._emit("event",e)},js=function(e){switch(e.event){case"thread.run.step.created":return Hs(this,bs,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Hs(this,bs,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Ls.accumulateDelta(t,n.delta);Hs(this,bs,"f")[e.data.id]=s}return Hs(this,bs,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Hs(this,bs,"f")[e.data.id]=e.data}if(Hs(this,bs,"f")[e.data.id])return Hs(this,bs,"f")[e.data.id];throw new Error("No snapshot available")},qs=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=Hs(this,ys,"m",Ts).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ts=function(e,t){return Ls.accumulateDelta(t,e)},Js=function(e){switch(Fs(this,ks,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Fs(this,Ss,e.data,"f"),Hs(this,Os,"f")&&(this._emit("toolCallDone",Hs(this,Os,"f")),Fs(this,Os,void 0,"f"))}};class Ms extends Bn{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/assistants",Bs,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Bs extends Mn{}function Ks(e){return"function"==typeof e.parse}Ms.AssistantsPage=Bs;const Ws=e=>"assistant"===e?.role,zs=e=>"function"===e?.role,Us=e=>"tool"===e?.role;function Vs(e){return"auto-parseable-response-format"===e?.$brand}function Gs(e){return"auto-parseable-tool"===e?.$brand}function Ys(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new Bt;if("content_filter"===e.finish_reason)throw new Kt;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const n=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Gs(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Xs(t,e.message.content):null}}});return{...e,choices:n}}function Xs(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function Qs(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return Gs(n)||n?.function.strict||!1}function Zs(e){return!!Vs(e.response_format)||(e.tools?.some(e=>Gs(e)||"function"===e.type&&!0===e.function.strict)??!1)}var er,tr,nr,sr,rr,ir,or,ar,lr=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};const cr=10;class ur extends gs{constructor(){super(...arguments),er.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(zs(e)||Us(e))&&e.content)this._emit("functionCallResult",e.content);else if(Ws(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Ws(e)&&e.tool_calls)for(const n of e.tool_calls)"function"===n.type&&this._emit("functionCall",n.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new It("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),lr(this,er,"m",tr).call(this)}async finalMessage(){return await this.done(),lr(this,er,"m",nr).call(this)}async finalFunctionCall(){return await this.done(),lr(this,er,"m",sr).call(this)}async finalFunctionCallResult(){return await this.done(),lr(this,er,"m",rr).call(this)}async totalUsage(){return await this.done(),lr(this,er,"m",ir).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=lr(this,er,"m",nr).call(this);t&&this._emit("finalMessage",t);const n=lr(this,er,"m",tr).call(this);n&&this._emit("finalContent",n);const s=lr(this,er,"m",sr).call(this);s&&this._emit("finalFunctionCall",s);const r=lr(this,er,"m",rr).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",lr(this,er,"m",ir).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),lr(this,er,"m",or).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ys(r,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:i,...o}=t,a="string"!=typeof r&&r?.name,{maxChatCompletions:l=cr}=n||{},c={};for(const d of t.functions)c[d.name||d.function.name]=d;const u=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(const d of t.messages)this._addMessage(d,!1);for(let d=0;d<l;++d){const t=await this._createChatCompletion(e,{...o,function_call:r,functions:u,messages:[...this.messages]},n),i=t.choices[0]?.message;if(!i)throw new It("missing message in ChatCompletion response");if(!i.function_call)return;const{name:l,arguments:d}=i.function_call,p=c[l];if(!p){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:l,content:e});continue}if(a&&a!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,name:l,content:e});continue}let f;try{f=Ks(p)?await p.parse(d):d}catch(h){this._addMessage({role:s,name:l,content:h instanceof Error?h.message:String(h)});continue}const m=await p.function(f,this),g=lr(this,er,"m",ar).call(this,m);if(this._addMessage({role:s,name:l,content:g}),a)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:i,...o}=t,a="string"!=typeof r&&r?.function?.name,{maxChatCompletions:l=cr}=n||{},c=t.tools.map(e=>{if(Gs(e)){if(!e.$callback)throw new It("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const p of c)"function"===p.type&&(u[p.function.name||p.function.function.name]=p.function);const h="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<l;++p){const t=await this._createChatCompletion(e,{...o,tool_choice:r,tools:h,messages:[...this.messages]},n),i=t.choices[0]?.message;if(!i)throw new It("missing message in ChatCompletion response");if(!i.tool_calls?.length)return;for(const e of i.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:n,arguments:r}=e.function,i=u[n];if(!i){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(a&&a!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let o;try{o=Ks(i)?await i.parse(r):r}catch(d){const e=d instanceof Error?d.message:String(d);this._addMessage({role:s,tool_call_id:t,content:e});continue}const l=await i.function(o,this),c=lr(this,er,"m",ar).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),a)return}}}}er=new WeakSet,tr=function(){return lr(this,er,"m",nr).call(this).content??null},nr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Ws(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new It("stream ended without producing a ChatCompletionMessage with role=assistant")},sr=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ws(t)&&t?.function_call)return t.function_call;if(Ws(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},rr=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(zs(t)&&null!=t.content)return t.content;if(Us(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},ir=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},or=function(e){if(null!=e.n&&e.n>1)throw new It("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ar=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class hr extends ur{static runFunctions(e,t,n){const s=new hr,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new hr,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}_addMessage(e,t=!0){super._addMessage(e,t),Ws(e)&&e.content&&this._emit("content",e.content)}}const dr=1,pr=2,fr=4,mr=8,gr=16,yr=32,wr=64,br=128,_r=256,vr=511;class Sr extends Error{}class $r extends Error{}const xr=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Sr(`${e} at position ${s}`)},i=e=>{throw new $r(`${e} at position ${s}`)},o=()=>(h(),s>=n&&r("Unexpected end of input"),'"'===e[s]?a():"{"===e[s]?l():"["===e[s]?c():"null"===e.substring(s,s+4)||gr&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||yr&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||yr&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||br&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||_r&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||wr&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):u()),a=()=>{const o=s;let a=!1;for(s++;s<n&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(o,++s-Number(a)))}catch(l){i(String(l))}else if(dr&t)try{return JSON.parse(e.substring(o,s-Number(a))+'"')}catch(l){return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,h();const i={};try{for(;"}"!==e[s];){if(h(),s>=n&&mr&t)return i;const r=a();h(),s++;try{const e=o();Object.defineProperty(i,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(l){if(mr&t)return i;throw l}h(),","===e[s]&&s++}}catch(l){if(mr&t)return i;r("Expected '}' at end of object")}return s++,i},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(o()),h(),","===e[s]&&s++}catch(i){if(fr&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&pr&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(a){if(pr&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(l){}i(String(a))}}const o=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||pr&t||r("Unterminated number literal");try{return JSON.parse(e.substring(o,s))}catch(a){"-"===e.substring(o,s)&&pr&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(l){i(String(l))}}},h=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return o()},Ar=e=>function(e,t=vr){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return xr(e.trim(),t)}(e,vr^pr);var Or,Nr,kr,Rr,Ir,Er,Cr,Pr,Dr,jr,qr,Tr,Jr=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Hr=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Fr extends ur{constructor(e){super(),Or.add(this),Nr.set(this,void 0),kr.set(this,void 0),Rr.set(this,void 0),Jr(this,Nr,e,"f"),Jr(this,kr,[],"f")}get currentChatCompletionSnapshot(){return Hr(this,Rr,"f")}static fromReadableStream(e){const t=new Fr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Fr(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Hr(this,Or,"m",Ir).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const i of r)Hr(this,Or,"m",Cr).call(this,i);if(r.controller.signal?.aborted)throw new Ct;return this._addChatCompletion(Hr(this,Or,"m",jr).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Hr(this,Or,"m",Ir).call(this),this._connected();const s=Qt.fromReadableStream(e,this.controller);let r;for await(const i of s)r&&r!==i.id&&this._addChatCompletion(Hr(this,Or,"m",jr).call(this)),Hr(this,Or,"m",Cr).call(this,i),r=i.id;if(s.controller.signal?.aborted)throw new Ct;return this._addChatCompletion(Hr(this,Or,"m",jr).call(this))}[(Nr=new WeakMap,kr=new WeakMap,Rr=new WeakMap,Or=new WeakSet,Ir=function(){this.ended||Jr(this,Rr,void 0,"f")},Er=function(e){let t=Hr(this,kr,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Hr(this,kr,"f")[e.index]=t,t)},Cr=function(e){if(this.ended)return;const t=Hr(this,Or,"m",Tr).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=Hr(this,Or,"m",Er).call(this,e);e.finish_reason&&(Hr(this,Or,"m",Dr).call(this,e),null!=s.current_tool_call_index&&Hr(this,Or,"m",Pr).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(Hr(this,Or,"m",Dr).call(this,e),null!=s.current_tool_call_index&&Hr(this,Or,"m",Pr).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type?this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):Mr(n?.type))}}},Pr=function(e,t){if(Hr(this,Or,"m",Er).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=Hr(this,Nr,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:Gs(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Dr=function(e){const t=Hr(this,Or,"m",Er).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=Hr(this,Or,"m",qr).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},jr=function(){if(this.ended)throw new It("stream has ended, this shouldn't happen");const e=Hr(this,Rr,"f");if(!e)throw new It("request ended without sending any chunks");return Jr(this,Rr,void 0,"f"),Jr(this,kr,[],"f"),function(e,t){const{id:n,choices:s,created:r,model:i,system_fingerprint:o,...a}=e,l={...a,id:n,choices:s.map(({message:t,finish_reason:n,index:s,logprobs:r,...i})=>{if(!n)throw new It(`missing finish_reason for choice ${s}`);const{content:o=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new It(`missing role for choice ${s}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new It(`missing function_call.arguments for choice ${s}`);if(!l)throw new It(`missing function_call.name for choice ${s}`);return{...i,message:{content:o,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return l?{...i,index:s,finish_reason:n,logprobs:r,message:{...c,role:u,content:o,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{const{function:r,type:i,id:o,...a}=t,{arguments:l,name:c,...u}=r||{};if(null==o)throw new It(`missing choices[${s}].tool_calls[${n}].id\n${Lr(e)}`);if(null==i)throw new It(`missing choices[${s}].tool_calls[${n}].type\n${Lr(e)}`);if(null==c)throw new It(`missing choices[${s}].tool_calls[${n}].function.name\n${Lr(e)}`);if(null==l)throw new It(`missing choices[${s}].tool_calls[${n}].function.arguments\n${Lr(e)}`);return{...a,id:o,type:i,function:{...u,name:c,arguments:l}}})}}:{...i,message:{...c,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}),created:r,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return function(e,t){return t&&Zs(t)?Ys(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(l,t)}(e,Hr(this,Nr,"f"))},qr=function(){const e=Hr(this,Nr,"f")?.response_format;return Vs(e)?e:null},Tr=function(e){var t,n,s,r;let i=Hr(this,Rr,"f");const{choices:o,...a}=e;i?Object.assign(i,a):i=Jr(this,Rr,{...a,choices:[]},"f");for(const{delta:l,finish_reason:c,index:u,logprobs:h=null,...d}of e.choices){let e=i.choices[u];if(e||(e=i.choices[u]={finish_reason:c,index:u,message:{},logprobs:h,...d}),h)if(e.logprobs){const{content:s,refusal:r,...i}=h;Object.assign(e.logprobs,i),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},h);if(c&&(e.finish_reason=c,Hr(this,Nr,"f")&&Zs(Hr(this,Nr,"f")))){if("length"===c)throw new Bt;if("content_filter"===c)throw new Kt}if(Object.assign(e,d),!l)continue;const{content:o,refusal:a,function_call:p,role:f,tool_calls:m,...g}=l;if(Object.assign(e.message,g),a&&(e.message.refusal=(e.message.refusal||"")+a),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),o&&(e.message.content=(e.message.content||"")+o,!e.message.refusal&&Hr(this,Or,"m",qr).call(this)&&(e.message.parsed=Ar(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:i,...o}of m){const a=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(a,o),n&&(a.id=n),s&&(a.type=s),i&&(a.function??(a.function={name:i.name??"",arguments:""})),i?.name&&(a.function.name=i.name),i?.arguments&&(a.function.arguments+=i.arguments,Qs(Hr(this,Nr,"f"),a)&&(a.function.parsed_arguments=Ar(a.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Lr(e){return JSON.stringify(e)}function Mr(e){}class Br extends Fr{static fromReadableStream(e){const t=new Br(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new Br(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new Br(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}}let Kr=class extends Bn{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new It(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new It(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>Ys(t,e))}runFunctions(e,t){return e.stream?Br.runFunctions(this._client,e,t):hr.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Br.runTools(this._client,e,t):hr.runTools(this._client,e,t)}stream(e,t){return Fr.createChatCompletion(this._client,e,t)}};class Wr extends Bn{constructor(){super(...arguments),this.completions=new Kr(this._client)}}(Wr||(Wr={})).Completions=Kr;class zr extends Bn{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Ur extends Bn{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Vr extends Bn{constructor(){super(...arguments),this.sessions=new zr(this._client),this.transcriptionSessions=new Ur(this._client)}}Vr.Sessions=zr,Vr.TranscriptionSessions=Ur;class Gr extends Bn{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Yr,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Yr extends Mn{}Gr.MessagesPage=Yr;class Xr extends Bn{retrieve(e,t,n,s={},r){return _n(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return _n(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Qr,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Qr extends Mn{}Xr.RunStepsPage=Qr;let Zr=class extends Bn{constructor(){super(...arguments),this.steps=new Xr(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,ei,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return Ls.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:i}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Rn(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return Ls.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return Ls.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class ei extends Mn{}Zr.RunsPage=ei,Zr.Steps=Xr,Zr.RunStepsPage=Qr;class ti extends Bn{constructor(){super(...arguments),this.runs=new Zr(this._client),this.messages=new Gr(this._client)}create(e={},t){return _n(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return Ls.createThreadAssistantStream(e,this._client.beta.threads,t)}}ti.Runs=Zr,ti.RunsPage=ei,ti.Messages=Gr,ti.MessagesPage=Yr;class ni extends Bn{constructor(){super(...arguments),this.realtime=new Vr(this._client),this.chat=new Wr(this._client),this.assistants=new Ms(this._client),this.threads=new ti(this._client)}}ni.Realtime=Vr,ni.Assistants=Ms,ni.AssistantsPage=Bs,ni.Threads=ti;class si extends Bn{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ri extends Bn{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}}let ii=class extends Bn{constructor(){super(...arguments),this.content=new ri(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,ln({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,oi,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}};class oi extends Mn{}ii.FileListResponsesPage=oi,ii.Content=ri;class ai extends Bn{constructor(){super(...arguments),this.files=new ii(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/containers",li,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class li extends Mn{}ai.ContainerListResponsesPage=li,ai.Files=ii,ai.FileListResponsesPage=oi;let ci=class extends Bn{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Tn("Request","User defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?r:(Tn("response","Decoding base64 embeddings to float32 array"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++)s[e]=t.charCodeAt(e);return Array.from(new Float32Array(s.buffer))}})(t)}),e)))}};class ui extends Bn{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return _n(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,hi,{query:n,...s})}}class hi extends Mn{}ui.OutputItemListResponsesPage=hi;class di extends Bn{constructor(){super(...arguments),this.outputItems=new ui(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,pi,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class pi extends Mn{}di.RunListResponsesPage=pi,di.OutputItems=ui,di.OutputItemListResponsesPage=hi;class fi extends Bn{constructor(){super(...arguments),this.runs=new di(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/evals",mi,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class mi extends Mn{}fi.EvalListResponsesPage=mi,fi.Runs=di,fi.RunListResponsesPage=pi;let gi=class extends Bn{create(e,t){return this._client.post("/files",ln({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/files",yi,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Rn(t),i=await this.retrieve(e),Date.now()-r>n)throw new Dt({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class yi extends Mn{}gi.FileObjectsPage=yi;class wi extends Bn{}let bi=class extends Bn{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class _i extends Bn{constructor(){super(...arguments),this.graders=new bi(this._client)}}_i.Graders=bi;class vi extends Bn{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Si,{body:t,method:"post",...n})}retrieve(e,t={},n){return _n(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Si extends Ln{}vi.PermissionCreateResponsesPage=Si;let $i=class extends Bn{constructor(){super(...arguments),this.permissions=new vi(this._client)}};$i.Permissions=vi,$i.PermissionCreateResponsesPage=Si;class xi extends Bn{list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Ai,{query:t,...n})}}class Ai extends Mn{}xi.FineTuningJobCheckpointsPage=Ai;class Oi extends Bn{constructor(){super(...arguments),this.checkpoints=new xi(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Ni,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return _n(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,ki,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class Ni extends Mn{}class ki extends Mn{}Oi.FineTuningJobsPage=Ni,Oi.FineTuningJobEventsPage=ki,Oi.Checkpoints=xi,Oi.FineTuningJobCheckpointsPage=Ai;class Ri extends Bn{constructor(){super(...arguments),this.methods=new wi(this._client),this.jobs=new Oi(this._client),this.checkpoints=new $i(this._client),this.alpha=new _i(this._client)}}Ri.Methods=wi,Ri.Jobs=Oi,Ri.FineTuningJobsPage=Ni,Ri.FineTuningJobEventsPage=ki,Ri.Checkpoints=$i,Ri.Alpha=_i;class Ii extends Bn{}class Ei extends Bn{constructor(){super(...arguments),this.graderModels=new Ii(this._client)}}Ei.GraderModels=Ii;class Ci extends Bn{createVariation(e,t){return this._client.post("/images/variations",ln({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ln({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Pi extends Bn{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Di,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Di extends Ln{}Pi.ModelsPage=Di;class ji extends Bn{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function qi(e,t){return t&&function(e){if(Vs(e.text?.format))return!0;return!1}(t)?Ti(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function Ti(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:Hi(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:Ji(t,e.text)}:e);return{...e,content:n}}return e}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Fi(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function Ji(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function Hi(e,t){const n=(s=e.tools??[],r=t.name,s.find(e=>"function"===e.type&&e.name===r));var s,r,i;return{...t,...t,parsed_arguments:(i=n,"auto-parseable-tool"===i?.$brand?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null)}}function Fi(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class Li extends Bn{list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,eo,{query:t,...n})}}var Mi,Bi,Ki,Wi,zi,Ui,Vi,Gi,Yi=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Xi=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Qi extends gs{constructor(e){super(),Mi.add(this),Bi.set(this,void 0),Ki.set(this,void 0),Wi.set(this,void 0),Yi(this,Bi,e,"f")}static createResponse(e,t,n){const s=new Qi(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Xi(this,Mi,"m",zi).call(this);let i=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const o of r)Xi(this,Mi,"m",Ui).call(this,o,i);if(r.controller.signal?.aborted)throw new Ct;return Xi(this,Mi,"m",Vi).call(this)}[(Bi=new WeakMap,Ki=new WeakMap,Wi=new WeakMap,Mi=new WeakSet,zi=function(){this.ended||Yi(this,Ki,void 0,"f")},Ui=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},s=Xi(this,Mi,"m",Gi).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=s.output[e.output_index];if(!t)throw new It(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new It(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new It(`expected content to be 'output_text', got ${s.type}`);n("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=s.output[e.output_index];if(!t)throw new It(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Vi=function(){if(this.ended)throw new It("stream has ended, this shouldn't happen");const e=Xi(this,Ki,"f");if(!e)throw new It("request ended without sending any events");Yi(this,Ki,void 0,"f");const t=function(e,t){return qi(e,t)}(e,Xi(this,Bi,"f"));return Yi(this,Wi,t,"f"),t},Gi=function(e){let t=Xi(this,Ki,"f");if(!t){if("response.created"!==e.type)throw new It(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=Yi(this,Ki,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new It(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new It(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new It(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new It(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new It(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":Yi(this,Ki,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Xi(this,Wi,"f");if(!e)throw new It("stream ended without producing a ChatCompletion");return e}}class Zi extends Bn{constructor(){super(...arguments),this.inputItems=new Li(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&Fi(e),e))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Ti(t,e))}stream(e,t){return Qi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class eo extends Mn{}Zi.InputItems=Li;class to extends Bn{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,ln({body:t,...n}))}}class no extends Bn{constructor(){super(...arguments),this.parts=new to(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}no.Parts=to;class so extends Bn{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return _n(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,ro,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=r.data;switch(i.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Rn(e);break;case"failed":case"completed":return i}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,io,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class ro extends Mn{}class io extends Ln{}so.VectorStoreFilesPage=ro,so.FileContentResponsesPage=io;class oo extends Bn{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return _n(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,ro,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Rn(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=s?.maxConcurrency??5,i=Math.min(r,t.length),o=this._client,a=t.values(),l=[...n];const c=Array(i).fill(a).map(async function(e){for(let t of e){const e=await o.files.create({file:t,purpose:"assistants"},s);l.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),n=t.filter(e=>"rejected"===e.status);if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of t)"fulfilled"===r.status&&s.push(r.value);return s})(c),await this.createAndPoll(e,{file_ids:l})}}class ao extends Bn{constructor(){super(...arguments),this.files=new so(this._client),this.fileBatches=new oo(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return _n(e)?this.list({},e):this._client.getAPIList("/vector_stores",lo,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,co,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class lo extends Mn{}class co extends Ln{}var uo;ao.VectorStoresPage=lo,ao.VectorStoreSearchResponsesPage=co,ao.Files=so,ao.VectorStoreFilesPage=ro,ao.FileContentResponsesPage=io,ao.FileBatches=oo;class ho extends mn{constructor({baseURL:e=Cn("OPENAI_BASE_URL"),apiKey:t=Cn("OPENAI_API_KEY"),organization:n=Cn("OPENAI_ORG_ID")??null,project:s=Cn("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new It("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new It("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new si(this),this.chat=new Vn(this),this.embeddings=new ci(this),this.files=new gi(this),this.images=new Ci(this),this.audio=new Qn(this),this.moderations=new ji(this),this.models=new Pi(this),this.fineTuning=new Ri(this),this.graders=new Ei(this),this.vectorStores=new ao(this),this.beta=new ni(this),this.batches=new Zn(this),this.uploads=new no(this),this.responses=new Zi(this),this.evals=new fi(this),this.containers=new ai(this),this._options=i,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return gt(e,{arrayFormat:"brackets"})}}uo=ho,ho.OpenAI=uo,ho.DEFAULT_TIMEOUT=6e5,ho.OpenAIError=It,ho.APIError=Et,ho.APIConnectionError=Pt,ho.APIConnectionTimeoutError=Dt,ho.APIUserAbortError=Ct,ho.NotFoundError=Jt,ho.ConflictError=Ht,ho.RateLimitError=Lt,ho.BadRequestError=jt,ho.AuthenticationError=qt,ho.InternalServerError=Mt,ho.PermissionDeniedError=Tt,ho.UnprocessableEntityError=Ft,ho.toFile=sn,ho.fileFromPath=At,ho.Completions=si,ho.Chat=Vn,ho.ChatCompletionsPage=zn,ho.Embeddings=ci,ho.Files=gi,ho.FileObjectsPage=yi,ho.Images=Ci,ho.Audio=Qn,ho.Moderations=ji,ho.Models=Pi,ho.ModelsPage=Di,ho.FineTuning=Ri,ho.Graders=Ei,ho.VectorStores=ao,ho.VectorStoresPage=lo,ho.VectorStoreSearchResponsesPage=co,ho.Beta=ni,ho.Batches=Zn,ho.BatchesPage=es,ho.Uploads=no,ho.Responses=Zi,ho.Evals=fi,ho.EvalListResponsesPage=mi,ho.Containers=ai,ho.ContainerListResponsesPage=li;class po{constructor(e,t={}){if(!e)throw new Error("OpenAI API key is required");this.openai=new ho({apiKey:e}),this.model=t.model||"gpt-4o-mini",this.maxTokens=t.maxTokens||2e3,this.temperature=t.temperature||.7}async sendMessage(e,t,n={}){try{const s=await this.openai.chat.completions.create({model:n.model||this.model,messages:[{role:"system",content:e},{role:"user",content:t}],max_tokens:n.maxTokens||this.maxTokens,temperature:n.temperature??this.temperature});return s.choices[0]?.message?.content?.trim()||""}catch(s){throw new Error(`LLM request failed: ${s.message}`)}}async chat(e,t={}){try{const n=await this.openai.chat.completions.create({model:t.model||this.model,messages:e,max_tokens:t.maxTokens||this.maxTokens,temperature:t.temperature??this.temperature});return n.choices[0]?.message?.content?.trim()||""}catch(n){throw new Error(`LLM chat failed: ${n.message}`)}}async summarize(e,t={}){const n=`You are a helpful assistant that summarizes text concisely while preserving key information. Keep summaries clear and focused.${t.maxLength?` Keep the summary under ${t.maxLength} words.`:""}${t.style?` Style: ${t.style}.`:""}`;return this.sendMessage(n,e,{temperature:.5})}async analyze(e,t){const n=`You are an expert analyst. Analyze the following text from the perspective of "${t}". Provide a clear, structured analysis.`;return this.sendMessage(n,e,{temperature:.3})}async extractKeywords(e,t=10){const n=`Extract the ${t} most important keywords or key phrases from the text. Return ONLY a JSON array of strings, nothing else. Example: ["keyword1", "keyword2"]`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split(",").map(e=>e.trim().replace(/["\[\]]/g,""))}}async categorize(e,t){const n=`Categorize the following text into one of these categories: ${t.join(", ")}.\nReturn ONLY a JSON object with: {"category": "chosen_category", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\{[\s\S]*\}/);return e?JSON.parse(e[0]):{category:t[0],confidence:.5,reasoning:s}}}async translate(e,t){const n=`Translate the following text to ${t}. Return ONLY the translation, nothing else.`;return this.sendMessage(n,e,{temperature:.3})}async generateQuestions(e,t=5){const n=`Generate ${t} insightful questions about the following text. Return ONLY a JSON array of question strings, nothing else. Example: ["Question 1?", "Question 2?"]`,s=await this.sendMessage(n,e,{temperature:.7});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split("\n").filter(e=>e.trim().endsWith("?"))}}async getJSON(e,t,n={}){const s=await this.sendMessage(e+"\n\nReturn ONLY valid JSON, no additional text.",t,{...n,temperature:n.temperature??.2});try{return JSON.parse(s)}catch{const e=s.match(/[\[{][\s\S]*[\]}]/);if(e)return JSON.parse(e[0]);throw new Error(`Failed to parse JSON response: ${s.substring(0,100)}`)}}}class fo{constructor(e){this.llm=e}async extractToSchema(e,t,n={}){const s=this._describeSchema(t),r=`You are a data extraction expert. Extract structured information from the provided text according to this JSON schema:\n\n${JSON.stringify(t,null,2)}\n\nSchema field descriptions:\n${s}\n\nRules:\n1. Extract ONLY information present in the text\n2. Use null for fields where information is not available\n3. Follow the exact schema structure and field types\n4. For arrays, include all relevant items found\n5. Return ONLY valid JSON matching the schema`;return await this.llm.getJSON(r,e,{temperature:.2,maxTokens:n.maxTokens||2e3})}_describeSchema(e,t=""){const n=[];if(e.description&&n.push(`${t||"root"}: ${e.description}`),e.properties)for(const[s,r]of Object.entries(e.properties)){const i=t?`${t}.${s}`:s,o=r.type||"any",a=e.required?.includes(s)?" (required)":"",l=r.description||"";n.push(`- ${i} [${o}]${a}: ${l}`),"object"===r.type&&r.properties&&n.push(this._describeSchema(r,i)),"array"===r.type&&r.items&&r.items.properties&&n.push(this._describeSchema(r.items,`${i}[]`))}return n.join("\n")}async extractMultiple(e,t,n={}){const s=`You are a data extraction expert. Extract ALL items matching this schema from the text:\n\n${JSON.stringify(t,null,2)}\n\nReturn a JSON array of all items found. If no items found, return [].\nReturn ONLY valid JSON array.`,r=await this.llm.getJSON(s,e,{temperature:.2,maxTokens:n.maxTokens||3e3});return Array.isArray(r)?r:[r]}async fillMissing(e,t,n){const s=this._findMissingFields(e,n);if(0===s.length)return e;const r=`You have existing data:\n${JSON.stringify(e,null,2)}\n\nExtract ONLY the following missing fields from the text:\n${s.join(", ")}\n\nBased on this schema:\n${JSON.stringify(n,null,2)}\n\nReturn JSON with ONLY the missing fields that you can extract. Do not modify existing fields.`,i=await this.llm.getJSON(r,t,{temperature:.2});return{...e,...i}}_findMissingFields(e,t,n=""){const s=[];if(t.properties)for(const[r,i]of Object.entries(t.properties)){const t=n?`${n}.${r}`:r,o=e[r];null==o?s.push(t):"object"===i.type&&i.properties&&s.push(...this._findMissingFields(o,i,t))}return s}validateExtraction(e,t){const n=[];if(t.required)for(const s of t.required)void 0!==e[s]&&null!==e[s]||n.push(`Missing required field: ${s}`);if(t.properties)for(const[s,r]of Object.entries(t.properties)){const t=e[s];if(null!=t){this._validateType(t,r.type)||n.push(`Invalid type for ${s}: expected ${r.type}, got ${typeof t}`)}}return{valid:0===n.length,errors:n}}_validateType(e,t){switch(t){case"string":return"string"==typeof e;case"number":case"integer":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"array":return Array.isArray(e);case"object":return"object"==typeof e&&!Array.isArray(e);default:return!0}}}class mo{constructor(e){this.llm=e}async add(e,t,n={}){const s=`You are a JSON merge expert. Semantically merge these two JSON objects.\n\nRules:\n1. Combine information from both objects intelligently\n2. For conflicting values, prefer the more complete/detailed one${n.preferSecond?", or prefer the second object":""}\n3. Merge arrays by combining items, removing duplicates by semantic similarity\n4. Preserve all unique information from both objects\n5. Return ONLY valid JSON`,r=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON(s,r,{temperature:.2})}async subtract(e,t){const n=`Base object (to modify):\n${JSON.stringify(e,null,2)}\n\nConcepts to remove:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON manipulation expert. Remove concepts from the first object that are semantically present in the second object.\n\nRules:\n1. Remove fields from obj1 that have semantic equivalents in obj2\n2. For arrays, remove items that are semantically similar to items in obj2\n3. Preserve fields/items in obj1 that have no semantic match in obj2\n4. Remove nested content that matches semantically\n5. Return ONLY valid JSON",n,{temperature:.2})}async union(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON merge expert. Create a semantic union of these two JSON objects.\n\nRules:\n1. Include all unique information from both objects\n2. For duplicate concepts, keep only one (the more complete version)\n3. Deduplicate array items by semantic similarity, not just exact match\n4. Merge nested objects recursively with the same rules\n5. Return ONLY valid JSON",n,{temperature:.2})}async difference(e,t){const n=`Object 1 (original):\n${JSON.stringify(e,null,2)}\n\nObject 2 (new):\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON('You are a JSON comparison expert. Find the semantic differences between these two JSON objects.\n\nReturn a JSON object with:\n- "added": fields/values present in obj2 but not in obj1\n- "removed": fields/values present in obj1 but not in obj2\n- "changed": fields where the value changed (show both old and new)\n\nConsider semantic similarity - fields with different names but same meaning should be considered the same.\nReturn ONLY valid JSON with the structure: {"added": {}, "removed": {}, "changed": {}}',n,{temperature:.2})}async concatenate(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON concatenation expert. Concatenate these two JSON objects.\n\nRules:\n1. For string fields: append obj2 values to obj1 values with appropriate separators\n2. For array fields: append obj2 arrays to obj1 arrays\n3. For number fields: sum the values\n4. For object fields: recursively concatenate\n5. For boolean fields: use logical OR\n6. Preserve the structure of obj1\n7. Return ONLY valid JSON",n,{temperature:.2})}async intersection(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON comparison expert. Find the semantic intersection of these two JSON objects.\n\nRules:\n1. Return only fields/values that are semantically present in BOTH objects\n2. For arrays, return only items that have semantic matches in both\n3. Consider semantic similarity, not just exact matches\n4. Return ONLY valid JSON",n,{temperature:.2})}async transform(e,t){const n=`You are a JSON transformation expert. Transform this JSON object according to the target structure description.\n\nTarget structure: ${t}\n\nRules:\n1. Map existing fields to the new structure\n2. Preserve all information, reorganizing as needed\n3. Use appropriate type conversions\n4. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async simplify(e,t={}){const n=`You are a JSON simplification expert. Simplify this nested JSON object.\n\nRules:\n1. Flatten deeply nested structures where appropriate\n2. Combine redundant fields\n3. Remove null/empty values${t.keepEmpty?" (unless specified to keep)":""}\n4. Use clear, concise field names\n5. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async apply(e,t){const n=`You are a JSON manipulation expert. Apply the following operation to the JSON object:\n\nOperation: ${t}\n\nReturn ONLY valid JSON with the operation applied.`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}}class go{constructor(e,t=null){this.openai=e,this.holosphere=t,this.model="text-embedding-3-small",this.dimensions=1536}setHoloSphere(e){this.holosphere=e}async embed(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data[0].embedding}catch(t){throw new Error(`Embedding generation failed: ${t.message}`)}}async embedBatch(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data.map(e=>e.embedding)}catch(t){throw new Error(`Batch embedding failed: ${t.message}`)}}cosineSimilarity(e,t){if(e.length!==t.length)throw new Error("Vectors must have same length");let n=0,s=0,r=0;for(let i=0;i<e.length;i++)n+=e[i]*t[i],s+=e[i]*e[i],r+=t[i]*t[i];return n/(Math.sqrt(s)*Math.sqrt(r))}async storeWithEmbedding(e,t,n,s=null){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const r=s?n[s]:n.content||n.text||n.description||JSON.stringify(n);if(!r)throw new Error("No text found to embed");const i=await this.embed(r),o={...n,_embedding:i,_embeddedField:s||"auto",_embeddedAt:Date.now()};return await this.holosphere.put(e,t,o),o}async semanticSearch(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required for search");const{limit:r=10,threshold:i=.5}=s,o=await this.embed(e),a=await this.holosphere.getAll(t,n),l=[];for(const c of a)if(c._embedding){const e=this.cosineSimilarity(o,c._embedding);e>=i&&l.push({item:{...c,_embedding:void 0},similarity:e})}return l.sort((e,t)=>t.similarity-e.similarity),l.slice(0,r)}async findSimilar(e,t,n,s={}){const r=e.content||e.text||e.description||JSON.stringify(e);return this.semanticSearch(r,t,n,s)}async cluster(e,t=5){const n=await Promise.all(e.map(async e=>{if(e._embedding)return e;const t=e.content||e.text||e.description||JSON.stringify(e),n=await this.embed(t);return{...e,_embedding:n}}));return this._kMeans(n,t).map(e=>e.map(e=>({...e,_embedding:void 0})))}_kMeans(e,t,n=100){if(e.length<=t)return e.map(e=>[e]);let s=[...e].sort(()=>Math.random()-.5).slice(0,t).map(e=>[...e._embedding]),r=new Array(e.length);for(let o=0;o<n;o++){const n=e.map(e=>{let t=1/0,n=0;for(let r=0;r<s.length;r++){const i=1-this.cosineSimilarity(e._embedding,s[r]);i<t&&(t=i,n=r)}return n});if(JSON.stringify(n)===JSON.stringify(r))break;r=n;for(let i=0;i<t;i++){const t=e.filter((e,t)=>r[t]===i);if(t.length>0){s[i]=new Array(this.dimensions).fill(0);for(const e of t)for(let t=0;t<this.dimensions;t++)s[i][t]+=e._embedding[t];for(let e=0;e<this.dimensions;e++)s[i][e]/=t.length}}}const i=Array.from({length:t},()=>[]);return e.forEach((e,t)=>{i[r[t]].push(e)}),i.filter(e=>e.length>0)}}const yo=[{name:"Values & Worldview",prompt:"Answer from the embodied perspective of Values and Worldview - considering ethics, beliefs, culture, and meaning."},{name:"Health & Wellbeing",prompt:"Answer from the embodied perspective of Health & Wellbeing - considering physical, mental, and social health."},{name:"Food & Agriculture",prompt:"Answer from the embodied perspective of Food & Agriculture - considering food systems, nutrition, and farming."},{name:"Business & Trade",prompt:"Answer from the embodied perspective of Business & Trade - considering commerce, markets, and economic exchange."},{name:"Energy & Resources",prompt:"Answer from the embodied perspective of Energy & Resources - considering power, materials, and sustainability."},{name:"Climate & Environment",prompt:"Answer from the embodied perspective of Climate Change - considering environmental impact and adaptation."},{name:"Ecosystems & Biosphere",prompt:"Answer from the embodied perspective of Ecosystems & Biosphere - considering biodiversity and natural systems."},{name:"Water Availability",prompt:"Answer from the embodied perspective of Water Availability - considering water access, quality, and management."},{name:"Habitat & Infrastructure",prompt:"Answer from the embodied perspective of Habitat & Infrastructure - considering built environment and housing."},{name:"Economy & Wealth",prompt:"Answer from the embodied perspective of Economy & Wealth - considering prosperity, inequality, and resources."},{name:"Governance & Institutions",prompt:"Answer from the embodied perspective of Governance & Institutions - considering power, policy, and organization."},{name:"Community & Resilience",prompt:"Answer from the embodied perspective of Community & Resilience - considering social bonds and adaptability."}];class wo{constructor(e,t=null){this.llm=e,this.perspectives=t||yo}setPerspectives(e){this.perspectives=e}static getDefaultPerspectives(){return yo}async ask(e,t={}){const{parallel:n=!0,includeSummary:s=!0}=t,r=t.perspectives||this.perspectives;let i;if(n)i=await Promise.all(r.map(async t=>{const n=await this._askPerspective(e,t);return{perspective:t.name,answer:n}}));else{i=[];for(const t of r){const n=await this._askPerspective(e,t);i.push({perspective:t.name,answer:n})}}let o=null;return s&&(o=await this._summarize(e,i)),{question:e,perspectives:i,summary:o,timestamp:Date.now()}}async _askPerspective(e,t){const n=`You are a wise council member representing a specific perspective.\n\n${t.prompt}\n\nProvide thoughtful, nuanced answers that honor your unique perspective while being constructive and helpful. Be concise but insightful.`;return this.llm.sendMessage(n,e,{temperature:.7})}async _summarize(e,t){const n=`Question: ${e}\n\nPerspectives:\n${t.map(e=>`**${e.perspective}**: ${e.answer}`).join("\n\n")}`;return this.llm.sendMessage("You are a wise facilitator. Synthesize the following perspectives into a balanced summary that:\n1. Identifies common themes and agreements\n2. Notes important tensions or tradeoffs\n3. Provides actionable wisdom\n4. Remains neutral and balanced\n\nBe concise but comprehensive.",n,{temperature:.5})}static createPerspectives(e){return e.map(e=>({name:e,prompt:`Answer from the embodied perspective of ${e} - considering all aspects related to ${e.toLowerCase()}.`}))}async askCustom(e,t,n={}){const s=wo.createPerspectives(t);return this.ask(e,{...n,perspectives:s})}async askSingle(e,t){const n=this.perspectives.find(e=>e.name===t)||{name:t,prompt:`Answer from the perspective of ${t}.`};return this._askPerspective(e,n)}async debate(e,t,n=3){if(2!==t.length)throw new Error("Debate requires exactly 2 perspectives");const s=t.map(e=>this.perspectives.find(t=>t.name===e)||{name:e,prompt:`Argue from the perspective of ${e}.`}),r=[];let i=`Topic: ${e}`;for(let o=0;o<n;o++)for(const e of s){const t=`You are debating from the perspective of ${e.name}.\n${e.prompt}\nRespond to the previous arguments constructively, acknowledging good points but advocating for your perspective.`,n=await this.llm.sendMessage(t,i,{temperature:.7});r.push({perspective:e.name,round:o+1,response:n}),i+=`\n\n${e.name}: ${n}`}return{topic:e,perspectives:t,exchanges:r,conclusion:await this.llm.sendMessage("As a neutral moderator, summarize the key insights from this debate and identify areas of agreement and disagreement.",i,{temperature:.5})}}}const bo={ALLOY:"alloy",ECHO:"echo",FABLE:"fable",ONYX:"onyx",NOVA:"nova",SHIMMER:"shimmer"},_o={TTS_1:"tts-1",TTS_1_HD:"tts-1-hd"};class vo{constructor(e){this.openai=e,this.defaultVoice=bo.ECHO,this.defaultModel=_o.TTS_1}async speak(e,t={}){const{voice:n=this.defaultVoice,model:s=this.defaultModel,speed:r=1,responseFormat:i="mp3"}=t;try{const t=await this.openai.audio.speech.create({model:s,voice:n,input:e,speed:r,response_format:i}),o=await t.arrayBuffer();return Buffer.from(o)}catch(o){throw new Error(`TTS failed: ${o.message}`)}}async speakBase64(e,t={}){return(await this.speak(e,t)).toString("base64")}async speakDataUrl(e,t={}){const n=t.responseFormat||"mp3";return`data:${"mp3"===n?"audio/mpeg":`audio/${n}`};base64,${await this.speakBase64(e,t)}`}setDefaultVoice(e){if(!Object.values(bo).includes(e))throw new Error(`Invalid voice: ${e}. Use one of: ${Object.values(bo).join(", ")}`);this.defaultVoice=e}setDefaultModel(e){if(!Object.values(_o).includes(e))throw new Error(`Invalid model: ${e}. Use one of: ${Object.values(_o).join(", ")}`);this.defaultModel=e}static getVoices(){return Object.values(bo)}static getModels(){return Object.values(_o)}static estimateDuration(e,t=1){return 60*(e.split(/\s+/).length/150)/t}static splitText(e,t=4e3){if(e.length<=t)return[e];const n=[],s=e.split(/(?<=[.!?])\s+/);let r="";for(const i of s)(r+i).length>t?(r&&n.push(r.trim()),r=i):r+=(r?" ":"")+i;return r&&n.push(r.trim()),n}async speakLong(e,t={}){const n=vo.splitText(e,t.maxChars||4e3);return await Promise.all(n.map(e=>this.speak(e,t)))}}class So{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async parse(e,t={}){const n=`You are a query parser. Convert natural language queries into structured JSON filters for a geospatial database.\n\nAvailable holons: ${t.holons?.join(", ")||"any"}\nAvailable lenses: ${t.lenses?.join(", ")||"any"}\n\nReturn a JSON object with:\n{\n "holon": "holon_id or null",\n "lens": "lens_name or null",\n "filters": {\n "field_name": { "op": "eq|ne|gt|gte|lt|lte|contains|in", "value": value }\n },\n "sort": { "field": "field_name", "order": "asc|desc" } or null,\n "limit": number or null,\n "spatial": { "near": "location_name", "radius": "distance" } or null,\n "temporal": { "after": "date", "before": "date" } or null\n}\n\nExamples:\n- "show projects near Rome" -> { "lens": "projects", "spatial": { "near": "Rome" } }\n- "find quests with more than 10 participants" -> { "lens": "quests", "filters": { "participants": { "op": "gt", "value": 10 } } }`;return await this.llm.getJSON(n,e,{temperature:.2})}async execute(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required for query execution");const n=await this.parse(e,t.context);let s=[];if(n.holon&&n.lens)s=await this.holosphere.getAll(n.holon,n.lens);else if(n.lens&&t.holons)for(const r of t.holons){const e=await this.holosphere.getAll(r,n.lens);s.push(...e.map(e=>({...e,_holon:r})))}return n.filters&&(s=this._applyFilters(s,n.filters)),n.sort&&(s=this._applySort(s,n.sort)),n.limit&&(s=s.slice(0,n.limit)),{query:e,parsed:n,results:s,count:s.length}}_applyFilters(e,t){return e.filter(e=>{for(const[n,s]of Object.entries(t)){const t=this._getNestedValue(e,n);if(!this._matchCondition(t,s))return!1}return!0})}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_matchCondition(e,t){const{op:n,value:s}=t;switch(n){case"eq":return e===s;case"ne":return e!==s;case"gt":return e>s;case"gte":return e>=s;case"lt":return e<s;case"lte":return e<=s;case"contains":return String(e).toLowerCase().includes(String(s).toLowerCase());case"in":return Array.isArray(s)&&s.includes(e);default:return!0}}_applySort(e,t){const{field:n,order:s}=t,r="desc"===s?-1:1;return[...e].sort((e,t)=>{const s=this._getNestedValue(e,n),i=this._getNestedValue(t,n);return s<i?-1*r:s>i?1*r:0})}async suggest(e={}){const t=`Suggest 5 useful natural language queries for exploring geospatial data.\n\nAvailable holons: ${e.holons?.join(", ")||"geographic areas"}\nAvailable lenses: ${e.lenses?.join(", ")||"projects, quests, events, resources"}\n\nReturn ONLY a JSON array of query strings.`;return this.llm.getJSON(t,"Generate query suggestions",{temperature:.7})}async explain(e,t){const n=`You are a helpful data analyst. Explain the results of a query in natural language.\n\nOriginal query: ${e}\nNumber of results: ${t.length}\n\nProvide a brief, helpful summary of what was found.`,s=t.slice(0,5);return this.llm.sendMessage(n,`Results sample: ${JSON.stringify(s,null,2)}`,{temperature:.5})}}class $o{constructor(e,t=null){this.llm=e,this.holosphere=t,this.lensDescriptions=new Map}setHoloSphere(e){this.holosphere=e}registerLens(e,t,n=null){this.lensDescriptions.set(e,{description:t,schema:n})}registerLenses(e){for(const[t,n]of Object.entries(e))this.registerLens(t,n.description,n.schema)}async classifyToLens(e){const t=Array.from(this.lensDescriptions.entries());if(0===t.length)throw new Error("No lenses registered. Use registerLens() first.");const n=t.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),s="string"==typeof e?e:JSON.stringify(e,null,2),r=`You are a content classifier. Classify the following content into the most appropriate lens.\n\nAvailable lenses:\n${n}\n\nReturn JSON: {"lens": "lens_name", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`;return this.llm.getJSON(r,s,{temperature:.2})}async classifyMultiple(e,t=3){const n=Array.from(this.lensDescriptions.entries());if(0===n.length)throw new Error("No lenses registered");const s=n.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),r="string"==typeof e?e:JSON.stringify(e,null,2),i=`You are a content classifier. Classify the content into up to ${t} appropriate lenses, ranked by fit.\n\nAvailable lenses:\n${s}\n\nReturn JSON array: [{"lens": "name", "confidence": 0.0-1.0}, ...]\nOrder by confidence descending.`;return this.llm.getJSON(i,r,{temperature:.2})}async autoStore(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const n=await this.classifyToLens(t),s=await this.holosphere.put(e,n.lens,t);return{lens:n.lens,confidence:n.confidence,reasoning:n.reasoning,stored:!0,result:s}}async suggestNewLens(e){const t=`You are helping design a data organization system. Suggest a new lens (category) for this type of content.\n\nExisting lenses: ${Array.from(this.lensDescriptions.keys()).join(", ")}\n\nReturn JSON: {"name": "lens_name", "description": "what this lens contains"}\nUse lowercase_snake_case for names.`;return this.llm.getJSON(t,e,{temperature:.5})}async suggestSchema(e){const t=JSON.stringify(e,null,2);return this.llm.getJSON("You are a data modeling expert. Analyze this content and suggest a JSON schema for validating similar content.\n\nReturn a valid JSON schema with:\n- Type definitions\n- Required fields\n- Field descriptions\n- Reasonable constraints",t,{temperature:.3})}async validateForLens(e,t){const n=this.lensDescriptions.get(t);if(!n)throw new Error(`Lens not found: ${t}`);if(!n.schema){const s=`Validate if this content is appropriate for the "${t}" lens.\nLens description: ${n.description}\n\nReturn JSON: {"valid": true/false, "issues": ["issue1", "issue2"] or []}`;return this.llm.getJSON(s,JSON.stringify(e,null,2),{temperature:.2})}return{valid:!0,issues:[]}}async analyzeCollection(e){const t=await Promise.all(e.map(e=>this.classifyToLens(e))),n={};for(const s of t)n[s.lens]=(n[s.lens]||0)+1;return{total:e.length,byLens:n,classifications:t}}}class xo{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async analyzeRegion(e,t=null,n="general"){if(!this.holosphere)throw new Error("HoloSphere instance required");let s=[];s=t?await this.holosphere.getAll(e,t):await this.holosphere.getAll(e,"default");const r=JSON.stringify(s.slice(0,50),null,2),i=`You are a geospatial data analyst. Analyze the following data from a geographic region.\n\nRegion (holon): ${e}\nLens: ${t||"all"}\nAnalysis aspect: ${n}\nTotal items: ${s.length}\n\nProvide insights about:\n1. Key patterns and trends\n2. Notable clusters or concentrations\n3. Anomalies or outliers\n4. Recommendations for the region\n\nReturn JSON:\n{\n "summary": "brief overview",\n "patterns": ["pattern1", "pattern2"],\n "insights": ["insight1", "insight2"],\n "metrics": {"metric1": value},\n "recommendations": ["rec1", "rec2"],\n "confidence": 0.0-1.0\n}`,o=await this.llm.getJSON(i,r,{temperature:.3});return{holon:e,lens:t,aspect:n,dataCount:s.length,analysis:o,timestamp:Date.now()}}async compareRegions(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,n),r=await this.holosphere.getAll(t,n),i=`You are a comparative analyst. Compare data between two geographic regions.\n\nRegion 1 (${e}): ${s.length} items\nRegion 2 (${t}): ${r.length} items\nLens: ${n}\n\nAnalyze and compare:\n1. Similarities between regions\n2. Key differences\n3. Relative strengths of each region\n4. Opportunities for collaboration\n\nReturn JSON:\n{\n "summary": "brief comparison",\n "similarities": ["sim1", "sim2"],\n "differences": ["diff1", "diff2"],\n "region1_strengths": ["strength1"],\n "region2_strengths": ["strength1"],\n "collaboration_opportunities": ["opp1"],\n "metrics_comparison": {"metric": {"region1": val, "region2": val}}\n}`,o=`Region 1 data sample:\n${JSON.stringify(s.slice(0,25),null,2)}\n\nRegion 2 data sample:\n${JSON.stringify(r.slice(0,25),null,2)}`,a=await this.llm.getJSON(i,o,{temperature:.3});return{regions:[e,t],lens:n,dataCounts:{[e]:s.length,[t]:r.length},comparison:a,timestamp:Date.now()}}async spatialTrends(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t);let r=s;(n.start||n.end)&&(r=s.filter(e=>{const t=e.timestamp||e.created_at||e.date;if(!t)return!0;const s=new Date(t).getTime();return!(n.start&&s<new Date(n.start).getTime())&&!(n.end&&s>new Date(n.end).getTime())}));const i=`You are a trend analyst. Analyze temporal patterns in geographic data.\n\nRegion: ${e}\nLens: ${t}\nTime range: ${JSON.stringify(n)}\nItems analyzed: ${r.length}\n\nIdentify:\n1. Growth/decline trends\n2. Seasonal patterns\n3. Emerging themes\n4. Predictions\n\nReturn JSON:\n{\n "trends": [{"trend": "description", "direction": "up|down|stable", "strength": 0.0-1.0}],\n "patterns": ["pattern1"],\n "emerging_themes": ["theme1"],\n "predictions": ["pred1"],\n "summary": "overview"\n}`,o=await this.llm.getJSON(i,JSON.stringify(r.slice(0,50),null,2),{temperature:.3});return{holon:e,lens:t,timeRange:n,dataCount:r.length,trends:o,timestamp:Date.now()}}async findHotspots(e,t,n="count"){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=`You are a spatial analyst. Identify hotspots (areas of high concentration/activity) in geographic data.\n\nRegion: ${e}\nLens: ${t}\nMetric: ${n}\nData points: ${s.length}\n\nIdentify:\n1. High-activity areas\n2. Emerging areas\n3. Underserved areas\n4. Recommended focus areas\n\nReturn JSON:\n{\n "hotspots": [{"location": "desc", "intensity": 0.0-1.0, "type": "high_activity|emerging|underserved"}],\n "concentration_patterns": ["pattern1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(r,JSON.stringify(s.slice(0,50),null,2),{temperature:.3})}async generateReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=t.lenses||["default"],s={};for(const o of n)s[o]=await this.holosphere.getAll(e,o);const r=`You are a regional analyst. Generate a comprehensive report for this geographic region.\n\nRegion: ${e}\nData by lens: ${Object.entries(s).map(([e,t])=>`${e}: ${t.length} items`).join(", ")}\n\nGenerate a professional report including:\n1. Executive Summary\n2. Key Statistics\n3. Notable Patterns\n4. Opportunities\n5. Recommendations\n\nFormat as markdown.`,i={};for(const[o,a]of Object.entries(s))i[o]=a.slice(0,20);return this.llm.sendMessage(r,JSON.stringify(i,null,2),{temperature:.5,maxTokens:2e3})}}class Ao{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async smartUpcast(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{maxLevels:s=5,storeResults:i=!0}=n,o=await this.holosphere.getAll(e,t),a=await this._generateSummary(o,e,t),l=r.getResolution(e);if(l<=0||s<=0)return{holon:e,lens:t,summary:a,level:l};const c=r.cellToParent(e,l-1);i&&await this.holosphere.put(c,`${t}_summaries`,{id:e,childHolon:e,summary:a,dataCount:o.length,timestamp:Date.now()});const u=await this.smartUpcast(c,t,{...n,maxLevels:s-1});return{holon:e,lens:t,summary:a,dataCount:o.length,parent:u}}async _generateSummary(e,t,n){if(0===e.length)return{text:"No data in this region",stats:{count:0}};const s=`You are a data summarization expert. Create a concise summary of this geographic data.\n\nRegion: ${t}\nCategory: ${n}\nItems: ${e.length}\n\nGenerate:\n1. A brief text summary (2-3 sentences)\n2. Key statistics\n3. Notable items\n4. Themes/patterns\n\nReturn JSON:\n{\n "text": "summary text",\n "stats": {"count": n, "key_metric": value},\n "notable": ["item1", "item2"],\n "themes": ["theme1", "theme2"]\n}`;return this.llm.getJSON(s,JSON.stringify(e.slice(0,30),null,2),{temperature:.3})}async generateHolonSummary(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=["projects","quests","events","resources","default"],n={};for(const i of t)try{const t=await this.holosphere.getAll(e,i);t.length>0&&(n[i]=t)}catch{}const s=`You are a regional analyst. Generate a comprehensive summary of this geographic area.\n\nRegion: ${e}\nData available: ${Object.entries(n).map(([e,t])=>`${e}: ${t.length}`).join(", ")}\n\nGenerate a complete overview including:\n1. Executive summary\n2. Key activities and projects\n3. Community engagement\n4. Resources and assets\n5. Challenges and opportunities\n6. Overall health assessment\n\nReturn JSON:\n{\n "title": "Region Title",\n "executive_summary": "brief overview",\n "highlights": ["highlight1", "highlight2"],\n "activities": {"count": n, "summary": "text"},\n "community": {"engagement_level": "high|medium|low", "notes": "text"},\n "resources": ["resource1"],\n "challenges": ["challenge1"],\n "opportunities": ["opp1"],\n "health_score": 0.0-1.0,\n "recommendations": ["rec1"]\n}`,r={};for(const[i,o]of Object.entries(n))r[i]=o.slice(0,15);return{holon:e,summary:await this.llm.getJSON(s,JSON.stringify(r,null,2),{temperature:.4,maxTokens:2e3}),lensesAnalyzed:Object.keys(n),totalItems:Object.values(n).reduce((e,t)=>e+t.length,0),timestamp:Date.now()}}async aggregateChildren(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=r.getResolution(e),s=r.cellToChildren(e,n+1),i=[];for(const r of s.slice(0,7))try{const e=await this.holosphere.getAll(r,t);if(e.length>0){const n=await this._generateSummary(e,r,t);i.push({holon:r,summary:n})}}catch{}if(0===i.length)return{holon:e,summary:null,message:"No child data found"};const o=`You are aggregating summaries from child regions into a parent region summary.\n\nParent region: ${e}\nChild summaries: ${i.length}\n\nCreate an aggregated summary that:\n1. Synthesizes common themes\n2. Highlights regional diversity\n3. Identifies cross-cutting patterns\n4. Notes outliers\n\nReturn JSON:\n{\n "aggregated_summary": "text",\n "common_themes": ["theme1"],\n "regional_diversity": ["diff1"],\n "patterns": ["pattern1"],\n "total_activity": {"count": n, "trend": "growing|stable|declining"}\n}`,a=await this.llm.getJSON(o,JSON.stringify(i,null,2),{temperature:.3});return{holon:e,lens:t,childCount:i.length,summary:a,timestamp:Date.now()}}async comparePeriods(e,t,n,s){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t),i=(e,t)=>e.filter(e=>{const n=e.timestamp||e.created_at;if(!n)return!1;const s=new Date(n).getTime();return s>=new Date(t.start).getTime()&&s<=new Date(t.end).getTime()}),o=i(r,n),a=i(r,s),l=`Compare data between two time periods for a geographic region.\n\nRegion: ${e}\nPeriod 1: ${JSON.stringify(n)} - ${o.length} items\nPeriod 2: ${JSON.stringify(s)} - ${a.length} items\n\nAnalyze:\n1. Growth/decline\n2. New themes in period 2\n3. Themes that disappeared\n4. Key changes\n\nReturn JSON:\n{\n "growth_rate": percentage,\n "direction": "growth|decline|stable",\n "new_themes": ["theme1"],\n "disappeared": ["theme1"],\n "key_changes": ["change1"],\n "summary": "text"\n}`,c=`Period 1 data:\n${JSON.stringify(o.slice(0,20),null,2)}\n\nPeriod 2 data:\n${JSON.stringify(a.slice(0,20),null,2)}`;return this.llm.getJSON(l,c,{temperature:.3})}}class Oo{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async suggestFederations(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{candidateHolons:n=[],lens:s="default",maxSuggestions:r=5}=t,i=await this.holosphere.getAll(e,s);if(0===i.length)return{holon:e,suggestions:[],message:"No data in source holon"};const o=[];for(const c of n.slice(0,10))if(c!==e)try{const e=await this.holosphere.getAll(c,s);e.length>0&&o.push({holon:c,dataCount:e.length,dataSample:e.slice(0,10)})}catch{}if(0===o.length)return{holon:e,suggestions:[],message:"No candidate holons with data"};const a=`You are a federation advisor. Analyze which regions would benefit from federating (sharing data) with the source region.\n\nSource region: ${e}\nSource data count: ${i.length}\n\nConsider:\n1. Content similarity - similar topics benefit from shared visibility\n2. Complementary content - different but related content enables collaboration\n3. Geographic proximity relevance\n4. Potential for knowledge sharing\n\nReturn JSON array:\n[\n {\n "holon": "id",\n "score": 0.0-1.0,\n "reasoning": "why federate",\n "benefits": ["benefit1"],\n "type": "similarity|complementary|geographic"\n }\n]\n\nOrder by score descending, max ${r} suggestions.`,l=`Source data sample:\n${JSON.stringify(i.slice(0,15),null,2)}\n\nCandidate regions:\n${JSON.stringify(o,null,2)}`;return{holon:e,lens:s,suggestions:(await this.llm.getJSON(a,l,{temperature:.3})).slice(0,r),timestamp:Date.now()}}async analyzeFederationHealth(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t||!t.federation||0===t.federation.length)return{holon:e,health:"none",message:"No federations configured",score:0};const n=[];for(const i of t.federation.slice(0,5))try{const e=await this.holosphere.getAll(i,"default");n.push({holon:i,active:e.length>0,dataCount:e.length})}catch{n.push({holon:i,active:!1,error:!0})}const s=`You are a federation health analyst. Assess the health of this holon's federation relationships.\n\nSource holon: ${e}\nFederation partners: ${t.federation.length}\nActive federations: ${n.filter(e=>e.active).length}\n\nFederation details:\n${JSON.stringify(n,null,2)}\n\nAnalyze:\n1. Overall federation health\n2. Active vs inactive relationships\n3. Balance of the federation network\n4. Recommendations\n\nReturn JSON:\n{\n "health_score": 0.0-1.0,\n "status": "healthy|degraded|unhealthy",\n "active_count": n,\n "inactive_count": n,\n "issues": ["issue1"],\n "recommendations": ["rec1"],\n "summary": "text"\n}`,r=await this.llm.getJSON(s,"",{temperature:.3});return{holon:e,federation:t.federation,analysis:r,timestamp:Date.now()}}async optimizeFederation(e){const t=await this.analyzeFederationHealth(e);if("none"===t.health)return{holon:e,suggestions:["Consider establishing initial federations"]};const n=`Based on federation health analysis, suggest optimizations.\n\nHealth analysis:\n${JSON.stringify(t.analysis,null,2)}\n\nSuggest:\n1. Federations to strengthen\n2. Federations to reconsider\n3. New potential federations\n4. Data flow improvements\n\nReturn JSON:\n{\n "strengthen": ["holon_id"],\n "reconsider": ["holon_id"],\n "new_potential": ["description"],\n "improvements": ["improvement1"],\n "priority": "high|medium|low"\n}`;return this.llm.getJSON(n,"",{temperature:.4})}async analyzeDataFlow(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t)return{holon:e,message:"No federation configured"};const n=`Analyze the data flow patterns in a federation network.\n\nSource holon: ${e}\nFederated with: ${t.federation?.join(", ")||"none"}\nNotifies: ${t.notify?.join(", ")||"none"}\n\nConsider:\n1. Bidirectional vs unidirectional relationships\n2. Hub patterns (many connections)\n3. Data propagation paths\n4. Potential bottlenecks\n\nReturn JSON:\n{\n "flow_type": "bidirectional|unidirectional|mixed",\n "topology": "hub|mesh|chain|star",\n "propagation_depth": n,\n "bottlenecks": ["desc"],\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(n,JSON.stringify(t,null,2),{temperature:.3})}async findBridges(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=[];for(const s of e.slice(0,20))try{const e=await this.holosphere.getFederation(s);e&&t.push({holon:s,federations:e.federation||[],notifies:e.notify||[]})}catch{}const n=`Analyze a federation network to identify bridge holons (connectors between clusters).\n\nNetwork:\n${JSON.stringify(t,null,2)}\n\nIdentify:\n1. Bridge holons that connect clusters\n2. Isolated holons\n3. Central hubs\n4. Network clusters\n\nReturn JSON:\n{\n "bridges": [{"holon": "id", "connects": ["cluster1", "cluster2"]}],\n "isolated": ["holon_id"],\n "hubs": [{"holon": "id", "connections": n}],\n "clusters": [["holon1", "holon2"]],\n "network_health": 0.0-1.0\n}`;return this.llm.getJSON(n,"",{temperature:.3})}}class No{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async discoverRelationships(e,t=null){if(!this.holosphere)throw new Error("HoloSphere instance required");let n=[];const s=t?[t]:["projects","quests","events","resources","default"];for(const o of s)try{const t=await this.holosphere.getAll(e,o);n.push(...t.map(e=>({...e,_lens:o})))}catch{}if(n.length<2)return{holon:e,relationships:[],message:"Not enough data for relationship discovery"};const r=`You are a relationship discovery expert. Find hidden connections between items in this dataset.\n\nRegion: ${e}\nItems: ${n.length}\n\nLook for:\n1. Thematic connections (shared topics, goals)\n2. Entity connections (shared people, organizations)\n3. Temporal connections (same timeframes)\n4. Causal connections (one enables/requires another)\n5. Geographic connections (same sub-regions)\n\nReturn JSON:\n{\n "relationships": [\n {\n "item1": {"id": "id1", "title": "title"},\n "item2": {"id": "id2", "title": "title"},\n "type": "thematic|entity|temporal|causal|geographic",\n "strength": 0.0-1.0,\n "description": "relationship description"\n }\n ],\n "clusters": [\n {\n "theme": "cluster theme",\n "items": ["id1", "id2"]\n }\n ],\n "key_entities": ["entity1", "entity2"],\n "summary": "overview of relationship network"\n}`,i=await this.llm.getJSON(r,JSON.stringify(n.slice(0,40),null,2),{temperature:.3});return{holon:e,lens:t,itemCount:n.length,relationships:i,timestamp:Date.now()}}async findSimilar(e,t=null,n=null,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{limit:r=10,threshold:i=.5,useEmbeddings:o=!0}=s;if(o&&this.embeddings&&t&&n)return this.embeddings.findSimilar(e,t,n,{limit:r,threshold:i});if(!t)throw new Error("Holon required for LLM-based similarity");const a=n?[n]:["projects","quests","events","resources","default"];let l=[];for(const u of a)try{const e=await this.holosphere.getAll(t,u);l.push(...e.map(e=>({...e,_lens:u})))}catch{}if(0===l.length)return[];const c=`Find items most similar to the reference item.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nConsider:\n1. Topic/theme similarity\n2. Goal alignment\n3. Participant overlap\n4. Resource requirements\n5. Timeline compatibility\n\nReturn JSON array of similar items with similarity scores:\n[\n {\n "item": {item object},\n "similarity": 0.0-1.0,\n "reasons": ["reason1"]\n }\n]\n\nOrder by similarity descending. Max ${r} items with similarity >= ${i}.`;return(await this.llm.getJSON(c,JSON.stringify(l.slice(0,50),null,2),{temperature:.2})).slice(0,r).filter(e=>e.similarity>=i)}async buildGraph(e,t){const n=await this.discoverRelationships(e,t),s=new Map,r=[];for(const i of n.relationships?.relationships||[])s.has(i.item1.id)||s.set(i.item1.id,{id:i.item1.id,label:i.item1.title}),s.has(i.item2.id)||s.set(i.item2.id,{id:i.item2.id,label:i.item2.title}),r.push({source:i.item1.id,target:i.item2.id,type:i.type,weight:i.strength});return{nodes:Array.from(s.values()),edges:r,clusters:n.relationships?.clusters||[]}}async findCrossHolonRelationships(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n={};for(const r of e.slice(0,5))try{const e=await this.holosphere.getAll(r,t);e.length>0&&(n[r]=e.slice(0,15))}catch{}if(Object.keys(n).length<2)return{message:"Need at least 2 holons with data"};const s=`Find relationships between items across different geographic regions.\n\nRegions and their data:\n${JSON.stringify(n,null,2)}\n\nIdentify:\n1. Cross-region collaborations\n2. Shared themes across regions\n3. Potential synergies\n4. Knowledge transfer opportunities\n\nReturn JSON:\n{\n "cross_relationships": [\n {\n "holon1": "id",\n "item1": "item_id",\n "holon2": "id",\n "item2": "item_id",\n "type": "type",\n "potential": "collaboration|knowledge_share|synergy"\n }\n ],\n "shared_themes": [{"theme": "theme", "holons": ["id1", "id2"]}],\n "opportunities": ["opp1"]\n}`;return this.llm.getJSON(s,"",{temperature:.4})}async suggestConnections(e,t,n){const s=await this.findSimilar(e,t,n,{limit:10}),r=`Based on similar items found, suggest specific actions to create connections.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nSimilar items found:\n${JSON.stringify(s,null,2)}\n\nSuggest:\n1. Collaboration opportunities\n2. Resource sharing possibilities\n3. Joint initiatives\n4. Knowledge exchange\n\nReturn JSON:\n{\n "collaborations": [{"with": "item_id", "action": "suggested action"}],\n "resource_sharing": [{"items": ["id1", "id2"], "resource": "what to share"}],\n "initiatives": [{"description": "joint initiative", "participants": ["id1"]}],\n "knowledge_exchange": [{"from": "id", "to": "id", "topic": "topic"}]\n}`;return this.llm.getJSON(r,"",{temperature:.5})}async detectPatterns(e,t){const n=await this.discoverRelationships(e,t),s=`Analyze relationships and detect higher-level patterns.\n\nRelationships:\n${JSON.stringify(n.relationships,null,2)}\n\nDetect:\n1. Hub-spoke patterns (central connectors)\n2. Cluster patterns (tight groups)\n3. Bridge patterns (connecting different groups)\n4. Chain patterns (sequential relationships)\n5. Cyclical patterns (mutual dependencies)\n\nReturn JSON:\n{\n "patterns": [\n {\n "type": "hub|cluster|bridge|chain|cycle",\n "description": "pattern description",\n "items": ["id1", "id2"],\n "significance": "why this matters"\n }\n ],\n "network_structure": "description of overall structure",\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(s,"",{temperature:.3})}}class ko{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async breakdown(e,t,n,s={}){if(!e||!e.id)throw new Error("Item must have an id property");const{depth:r=2,stepsPerLevel:i={min:3,max:5},useContext:o=!0,storeResults:a=!0,dependencyField:l="dependencies",parentField:c="parent"}=s,u="number"==typeof i?{min:i,max:i}:i;let h=[];if(o&&this.holosphere)try{h=(await this.holosphere.getAll(t,n)).filter(t=>t.id!==e.id).slice(0,10)}catch{}let d=null;if(this.holosphere)try{d=await this.holosphere.getSchema(n)}catch{}const p=await this._breakdownRecursive(e,t,n,r,u,h,d,l,c,a,0);return{original:e,holonId:t,lensName:n,breakdown:p,totalSubtasks:this._countSubtasks(p),maxDepth:r,timestamp:Date.now()}}async _breakdownRecursive(e,t,n,s,r,i,o,a,l,c,u){if(u>=s)return{item:e,children:[],depth:u};const h=await this._generateSubtasks(e,i,o,r,a,l);if(c&&this.holosphere&&h.length>0){for(const e of h)try{await this.holosphere.write(t,n,e)}catch(p){console.warn(`Failed to store subtask ${e.id}:`,p.message)}if(e._meta?.childTasks!==h.map(e=>e.id))try{await this.holosphere.update(t,n,e.id,{_meta:{...e._meta,childTasks:h.map(e=>e.id),breakdownTimestamp:Date.now()}})}catch{}}const d=[];for(const f of h){const e=await this._breakdownRecursive(f,t,n,s,r,i,o,a,l,c,u+1);d.push(e)}return{item:e,children:d,depth:u}}async _generateSubtasks(e,t,n,s,r,i){const{min:o,max:a}=s,l=`You are a task decomposition expert. Break down the given task/quest into ${o}-${a} concrete, actionable subtasks.\n\nEach subtask should:\n1. Be a clear, specific action\n2. Be smaller and more manageable than the parent\n3. Together with siblings, fully accomplish the parent task\n4. Have a unique ID (format: parentId-1, parentId-2, etc.)\n5. Reference the parent task in the "${i}" field\n6. List any dependencies on sibling tasks in "${r}" array\n\n${n?`Follow this schema structure:\n${JSON.stringify(n,null,2)}`:""}\n\n${t.length>0?`Consider these existing items for context and avoid duplication:\n${JSON.stringify(t.slice(0,5),null,2)}`:""}\n\nReturn a JSON array of subtasks. Each subtask must have:\n- id: unique identifier (parentId-1, parentId-2, etc.)\n- title/name: clear action title\n- description: what needs to be done\n- ${i}: reference to parent id\n- ${r}: array of sibling task ids this depends on (empty if first task)\n- status: "pending"\n- Any other relevant fields from the parent schema\n\nExample output format:\n[\n {\n "id": "parent-1",\n "title": "First subtask",\n "description": "Details...",\n "${i}": "parentId",\n "${r}": [],\n "status": "pending"\n },\n {\n "id": "parent-2",\n "title": "Second subtask (depends on first)",\n "description": "Details...",\n "${i}": "parentId",\n "${r}": ["parent-1"],\n "status": "pending"\n }\n]`,c=`Break down this task into ${o}-${a} subtasks:\n\n${JSON.stringify(e,null,2)}`;try{return(await this.llm.getJSON(l,c,{temperature:.4,maxTokens:2e3})).map((t,n)=>({...t,id:t.id||`${e.id}-${n+1}`,[i]:e.id,[r]:t[r]||[],status:t.status||"pending",_meta:{...t._meta,generatedFrom:e.id,generatedAt:Date.now(),depth:(e._meta?.depth||0)+1}}))}catch(u){return console.error("Failed to generate subtasks:",u),[]}}_countSubtasks(e){return e.children&&0!==e.children.length?e.children.length+e.children.reduce((e,t)=>e+this._countSubtasks(t),0):0}flatten(e){const t=[],n=e=>{if(e.item&&t.push(e.item),e.children)for(const t of e.children)n(t)};return e.breakdown&&n(e.breakdown),t}getDependencyOrder(e){return this.flatten(e).sort((e,t)=>{const n=e._meta?.depth||0,s=t._meta?.depth||0;if(n!==s)return n-s;if((t.dependencies||[]).includes(e.id))return-1;return(e.dependencies||[]).includes(t.id)?1:0})}async suggestStrategy(e){return this.llm.getJSON('You are a task decomposition expert. Analyze this task and suggest the best breakdown strategy.\n\nConsider:\n1. Task complexity\n2. Recommended depth (1-4 levels)\n3. Recommended subtasks per level (2-7)\n4. Key areas to focus on\n5. Potential dependencies between subtasks\n\nReturn JSON:\n{\n "complexity": "simple|moderate|complex|very_complex",\n "recommendedDepth": n,\n "recommendedStepsPerLevel": {"min": n, "max": n},\n "focusAreas": ["area1", "area2"],\n "potentialChallenges": ["challenge1"],\n "estimatedTotalSubtasks": n,\n "reasoning": "explanation"\n}',JSON.stringify(e,null,2),{temperature:.3})}async rebalance(e,t={}){const{targetStepsPerLevel:n={min:3,max:5}}=t,s=this.flatten(e),r=`You are a task organization expert. Rebalance these tasks to have ${n.min}-${n.max} items per level.\n\nCurrent tasks:\n${JSON.stringify(s,null,2)}\n\nReorganize by:\n1. Merging tasks that are too granular\n2. Splitting tasks that are too large\n3. Maintaining proper dependency chains\n4. Keeping the same overall scope\n\nReturn JSON with the rebalanced structure:\n{\n "tasks": [...],\n "changes": [{"type": "merge|split|move", "description": "..."}],\n "summary": "what changed"\n}`;return this.llm.getJSON(r,"",{temperature:.3})}async getProgress(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=s.find(e=>e.id===n);if(!r)throw new Error(`Item ${n} not found`);const i=this._findDescendants(n,s),o=i.length,a=i.filter(e=>"completed"===e.status||"done"===e.status).length,l=i.filter(e=>"in_progress"===e.status||"active"===e.status).length,c=o-a-l;return{itemId:n,title:r.title||r.name,total:o,completed:a,inProgress:l,pending:c,percentComplete:o>0?Math.round(a/o*100):0,blockers:this._findBlockers(i),nextUp:this._findNextTasks(i)}}_findDescendants(e,t,n="parent"){const s=[],r=t.filter(t=>t[n]===e);for(const i of r)s.push(i),s.push(...this._findDescendants(i.id,t,n));return s}_findBlockers(e,t="dependencies"){return e.filter(n=>{const s=n[t]||[];return 0!==s.length&&s.some(t=>{const n=e.find(e=>e.id===t);return n&&"completed"!==n.status&&"done"!==n.status})}).map(e=>({id:e.id,title:e.title||e.name,blockedBy:e[t]}))}_findNextTasks(e,t="dependencies"){return e.filter(n=>{if("completed"===n.status||"done"===n.status)return!1;if("in_progress"===n.status||"active"===n.status)return!1;const s=n[t]||[];return 0===s.length||s.every(t=>{const n=e.find(e=>e.id===t);return!n||"completed"===n.status||"done"===n.status})}).slice(0,5).map(e=>({id:e.id,title:e.title||e.name,description:e.description}))}}class Ro{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async suggestResolution(e,t={}){const{currentResolution:n=null,context:s=null}=t,r=`You are a geospatial planning expert. Analyze this item and suggest the optimal H3 hexagonal resolution (0-15) for organizing it.\n\nH3 Resolution Guide:\n- Resolution 0-2: Continental/country scale (thousands of km)\n- Resolution 3-4: Regional/state scale (hundreds of km)\n- Resolution 5-6: Metropolitan/city scale (tens of km)\n- Resolution 7-8: District/neighborhood scale (km)\n- Resolution 9-10: Block/street scale (hundreds of meters)\n- Resolution 11-12: Building/lot scale (tens of meters)\n- Resolution 13-15: Room/precise scale (meters)\n\nConsider:\n1. Geographic scope mentioned in the item\n2. Number of potential participants/stakeholders\n3. Type of activity (local vs regional)\n4. Resource requirements and logistics\n5. Similar projects' typical scale\n\n${null!==n?`Current resolution: ${n}`:""}\n${s?`Context:\n${JSON.stringify(s,null,2)}`:""}\n\nReturn JSON:\n{\n "recommendedResolution": n,\n "reasoning": "why this resolution",\n "alternativeResolutions": [{"resolution": n, "useCase": "when to use"}],\n "geographicScope": "description of area covered",\n "scaleSuggestions": {\n "expansion": {"resolution": n, "reason": "when to expand"},\n "contraction": {"resolution": n, "reason": "when to focus"}\n }\n}`;return this.llm.getJSON(r,JSON.stringify(e,null,2),{temperature:.3})}async analyzeDistribution(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{includeChildren:s=!0,maxChildren:i=20}=n,o=await this.holosphere.getAll(e,t),a={};if(s&&r.isValidCell(e)){const n=r.getResolution(e);if(n<15){const s=r.cellToChildren(e,n+1);for(const e of s.slice(0,i))try{const n=await this.holosphere.getAll(e,t);n.length>0&&(a[e]={count:n.length,sample:n.slice(0,3)})}catch{}}}const l=`You are a geospatial analyst. Analyze the distribution of data across this H3 hexagonal region.\n\nParent holon: ${e}\nResolution: ${r.isValidCell(e)?r.getResolution(e):"N/A"}\nParent data count: ${o.length}\nChildren with data: ${Object.keys(a).length}\n\nAnalyze:\n1. Data density and distribution patterns\n2. Geographic hotspots and cold spots\n3. Coverage gaps\n4. Clustering patterns\n5. Recommendations for better coverage\n\nReturn JSON:\n{\n "distribution": {\n "pattern": "clustered|uniform|sparse|concentrated",\n "density": "high|medium|low",\n "coverage": 0.0-1.0\n },\n "hotspots": [{"holonId": "id", "reason": "why"}],\n "gaps": [{"description": "gap description", "suggestedAction": "what to do"}],\n "clusters": [{"theme": "cluster theme", "holons": ["id1"]}],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`,c=`Parent data sample:\n${JSON.stringify(o.slice(0,10),null,2)}\n\nChildren distribution:\n${JSON.stringify(a,null,2)}`,u=await this.llm.getJSON(l,c,{temperature:.3});return{holonId:e,lensName:t,resolution:r.isValidCell(e)?r.getResolution(e):null,parentDataCount:o.length,childrenAnalyzed:Object.keys(a).length,analysis:u,timestamp:Date.now()}}async findNeighborRelevance(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{ringSize:s=1,relevanceThreshold:i=.5}=n,o=await this.holosphere.getAll(e,t),a=r.gridDisk(e,s).filter(t=>t!==e),l={};for(const r of a)try{const e=await this.holosphere.getAll(r,t);e.length>0&&(l[r]=e.slice(0,5))}catch{}if(0===Object.keys(l).length)return{holonId:e,neighbors:[],message:"No data found in neighboring cells"};const c=`You are a geospatial relevance analyst. Find items in neighboring H3 cells that are relevant to the center cell's data.\n\nCenter cell: ${e}\nRing size: ${s} (immediate neighbors)\n\nConsider:\n1. Thematic overlap\n2. Potential collaborations\n3. Shared resources\n4. Cross-boundary projects\n5. Geographic continuity of activities\n\nReturn JSON:\n{\n "relevantNeighbors": [\n {\n "holonId": "neighbor_id",\n "relevanceScore": 0.0-1.0,\n "relevantItems": [{"id": "item_id", "reason": "why relevant"}],\n "collaborationPotential": "description"\n }\n ],\n "crossBoundaryOpportunities": [\n {\n "description": "opportunity",\n "involvedHolons": ["id1", "id2"],\n "suggestedAction": "what to do"\n }\n ],\n "geographicPatterns": ["pattern1"],\n "summary": "overview"\n}`,u=`Center cell data:\n${JSON.stringify(o.slice(0,10),null,2)}\n\nNeighbor data:\n${JSON.stringify(l,null,2)}`,h=await this.llm.getJSON(c,u,{temperature:.4});return h.relevantNeighbors&&(h.relevantNeighbors=h.relevantNeighbors.filter(e=>e.relevanceScore>=i)),{holonId:e,lensName:t,ringSize:s,neighborsAnalyzed:Object.keys(l).length,analysis:h,timestamp:Date.now()}}async suggestGeographicScope(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const i=r.getResolution(t);let o=[];if(i>0){const e=r.cellToParent(t,i-1);try{o=await this.holosphere.getAll(e,n)}catch{}}let a=[];if(i<15){const e=r.cellToChildren(t,i+1);for(const t of e.slice(0,7))try{const e=await this.holosphere.getAll(t,n);a.push(...e.slice(0,2))}catch{}}const l=`You are a geographic scope advisor. Analyze whether this item should expand to a larger region (parent holon) or focus on smaller sub-regions (children holons).\n\nCurrent holon: ${t}\nCurrent resolution: ${i}\n\nFactors to consider:\n1. Item's stated scope and goals\n2. Current participation/activity level\n3. Resource requirements\n4. Similar activities in parent/children\n5. Natural geographic boundaries\n\nReturn JSON:\n{\n "currentScopeAssessment": {\n "appropriate": true/false,\n "reasoning": "why"\n },\n "expansionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why expand",\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "contractionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why contract",\n "suggestedFocusAreas": ["description"],\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "optimalAction": "expand|contract|maintain",\n "summary": "recommendation summary"\n}`,c=`Item to analyze:\n${JSON.stringify(e,null,2)}\n\nParent region data (${o.length} items):\n${JSON.stringify(o.slice(0,5),null,2)}\n\nChildren regions data (${a.length} items):\n${JSON.stringify(a.slice(0,5),null,2)}`;return this.llm.getJSON(l,c,{temperature:.3})}async analyzeCoverage(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{targetResolution:s=null}=n,i=r.getResolution(e),o=s||Math.min(i+1,15),a=r.cellToChildren(e,o),l={total:a.length,withData:0,withoutData:0,dataDistribution:{}},c=[],u=[];for(const r of a)try{const e=await this.holosphere.getAll(r,t);e.length>0?(l.withData++,l.dataDistribution[r]=e.length,c.push({holon:r,count:e.length})):(l.withoutData++,u.push(r))}catch{l.withoutData++,u.push(r)}const h=`You are a geographic coverage analyst. Analyze the data coverage in this H3 region.\n\nRegion: ${e}\nResolution: ${i}\nChild resolution analyzed: ${o}\nTotal children: ${l.total}\nChildren with data: ${l.withData}\nChildren without data: ${l.withoutData}\nCoverage ratio: ${(l.withData/l.total*100).toFixed(1)}%\n\nAnalyze:\n1. Coverage patterns\n2. Potential reasons for gaps\n3. Priority areas for expansion\n4. Whether gaps are concerning or expected\n\nReturn JSON:\n{\n "coverageScore": 0.0-1.0,\n "coverageQuality": "excellent|good|moderate|poor|minimal",\n "patterns": {\n "type": "clustered|scattered|peripheral|central|uniform",\n "description": "pattern description"\n },\n "gaps": {\n "count": n,\n "significance": "high|medium|low",\n "likelyReasons": ["reason1"],\n "priorityAreas": ["description of areas to focus"]\n },\n "recommendations": [\n {\n "action": "what to do",\n "priority": "high|medium|low",\n "targetArea": "description"\n }\n ],\n "summary": "overview"\n}`,d=await this.llm.getJSON(h,"",{temperature:.3});return{holonId:e,lensName:t,resolution:i,childResolution:o,coverage:{...l,ratio:l.withData/l.total},childrenWithData:c.slice(0,10),gapCount:u.length,analysis:d,timestamp:Date.now()}}async crossResolutionInsights(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{levels:s=3}=n,i=r.getResolution(e),o={},a=await this.holosphere.getAll(e,t);o[i]={holon:e,count:a.length,sample:a.slice(0,5)};let l=e;for(let u=0;u<s&&r.getResolution(l)>0;u++){const e=r.getResolution(l)-1;l=r.cellToParent(l,e);try{const n=await this.holosphere.getAll(l,t);o[e]={holon:l,count:n.length,sample:n.slice(0,5)}}catch{}}if(i<15){const n=i+1,s=r.cellToChildren(e,n);let a=0;const l=[];for(const e of s.slice(0,7))try{const n=await this.holosphere.getAll(e,t);a+=n.length,n.length>0&&l.push(...n.slice(0,2))}catch{}o[n]={holon:`${s.length} children`,count:a,sample:l.slice(0,5)}}const c=`You are a multi-scale geographic analyst. Find patterns that emerge across different H3 resolutions.\n\nStarting holon: ${e}\nResolutions analyzed: ${Object.keys(o).sort().join(", ")}\n\nData at each resolution:\n${JSON.stringify(o,null,2)}\n\nAnalyze:\n1. How themes evolve across scales\n2. What appears only at certain resolutions\n3. Aggregation patterns (local vs regional)\n4. Scale-dependent opportunities\n5. Optimal resolution for different activities\n\nReturn JSON:\n{\n "scalePatterns": [\n {\n "pattern": "description",\n "visibleAt": [resolution_numbers],\n "significance": "why this matters"\n }\n ],\n "themeEvolution": {\n "localThemes": ["themes at fine resolution"],\n "regionalThemes": ["themes at coarse resolution"],\n "consistentThemes": ["themes across all scales"]\n },\n "optimalResolutions": {\n "forCollaboration": n,\n "forResources": n,\n "forCommunity": n,\n "reasoning": "why"\n },\n "insights": ["insight1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(c,"",{temperature:.4})}async suggestMigration(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const{searchRadius:i=2}=s,o=r.gridDisk(t,i),a={};for(const r of o)if(r!==t)try{const e=await this.holosphere.getAll(r,n);e.length>0&&(a[r]={count:e.length,sample:e.slice(0,3)})}catch{}const l=r.getResolution(t);let c=null;if(l>0){const e=r.cellToParent(t,l-1);try{const t=await this.holosphere.getAll(e,n);c={holon:e,count:t.length,sample:t.slice(0,3)}}catch{}}const u=`You are a geographic placement advisor. Determine if this item would be better suited in a different H3 cell.\n\nCurrent location: ${t}\nCurrent resolution: ${l}\n\nConsider:\n1. Thematic fit with existing data in each cell\n2. Geographic scope of the item\n3. Collaboration opportunities\n4. Resource proximity\n5. Community alignment\n\nReturn JSON:\n{\n "currentFit": {\n "score": 0.0-1.0,\n "reasoning": "why current location is/isn't appropriate"\n },\n "migrationRecommended": true/false,\n "suggestedDestinations": [\n {\n "holonId": "cell_id",\n "fitScore": 0.0-1.0,\n "reasoning": "why this location",\n "benefits": ["benefit1"],\n "drawbacks": ["drawback1"]\n }\n ],\n "stayReasons": ["reason to stay if applicable"],\n "moveReasons": ["reason to move if applicable"],\n "recommendation": "stay|move|duplicate",\n "summary": "final recommendation"\n}`,h=`Item to place:\n${JSON.stringify(e,null,2)}\n\nNearby cells with data:\n${JSON.stringify(a,null,2)}\n\n${c?`Parent cell data:\n${JSON.stringify(c,null,2)}`:""}`;return this.llm.getJSON(u,h,{temperature:.3})}async generateGeographicReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{lenses:n=["projects","quests","events","resources","default"]}=t,s={};for(const r of n)try{const t=await this.holosphere.getAll(e,r);t.length>0&&(s[r]={count:t.length,sample:t.slice(0,5)})}catch{}let i={};if(r.isValidCell(e)){const t=r.getResolution(e),[n,s]=r.cellToLatLng(e),o=r.cellToBoundary(e);i={resolution:t,center:{lat:n,lng:s},areaKm2:r.cellArea(e,"km2"),vertexCount:o.length}}const o=`You are a regional activity reporter. Generate a comprehensive report on geographic activity in this H3 region.\n\nRegion: ${e}\nGeographic context: ${JSON.stringify(i,null,2)}\nData available in ${Object.keys(s).length} categories\n\nGenerate a report covering:\n1. Executive summary\n2. Activity overview by category\n3. Key highlights and achievements\n4. Geographic patterns\n5. Opportunities and challenges\n6. Recommendations\n\nReturn JSON:\n{\n "title": "Region Report Title",\n "executiveSummary": "2-3 sentence overview",\n "activityOverview": {\n "totalItems": n,\n "categorySummaries": {"lens": "summary"}\n },\n "highlights": [\n {"title": "highlight", "description": "details", "category": "lens"}\n ],\n "geographicPatterns": ["pattern1"],\n "strengths": ["strength1"],\n "challenges": ["challenge1"],\n "opportunities": ["opportunity1"],\n "recommendations": [\n {"priority": "high|medium|low", "action": "what to do", "rationale": "why"}\n ],\n "metrics": {\n "activityLevel": "high|medium|low",\n "diversity": "high|medium|low",\n "growth": "growing|stable|declining"\n }\n}`,a=await this.llm.getJSON(o,JSON.stringify(s,null,2),{temperature:.4,maxTokens:2e3});return{holonId:e,geoContext:i,lensesAnalyzed:Object.keys(s),totalItems:Object.values(s).reduce((e,t)=>e+t.count,0),report:a,timestamp:Date.now()}}async findGeographicClusters(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{clusterResolution:s=null}=n,i=r.getResolution(e),o=s||Math.min(i+1,15),a=r.cellToChildren(e,o),l={};for(const r of a)try{const e=await this.holosphere.getAll(r,t);e.length>0&&(l[r]=e)}catch{}if(Object.keys(l).length<2)return{holonId:e,clusters:[],message:"Not enough data for clustering"};const c=`You are a geographic clustering expert. Find thematic clusters in this spatial data.\n\nRegion: ${e}\nResolution analyzed: ${o}\nCells with data: ${Object.keys(l).length}\n\nIdentify:\n1. Thematic clusters (cells with similar content)\n2. Activity clusters (cells with related activities)\n3. Isolated cells (unique content)\n4. Potential connections between clusters\n\nReturn JSON:\n{\n "clusters": [\n {\n "name": "cluster name",\n "theme": "what unifies this cluster",\n "cells": ["cell_id1", "cell_id2"],\n "strength": 0.0-1.0,\n "characteristics": ["char1"]\n }\n ],\n "isolatedCells": [\n {"cellId": "id", "uniqueAspect": "what makes it unique"}\n ],\n "interClusterConnections": [\n {"cluster1": "name", "cluster2": "name", "connection": "how related"}\n ],\n "spatialPatterns": ["pattern1"],\n "recommendations": ["rec1"]\n}`,u=await this.llm.getJSON(c,JSON.stringify(l,null,2),{temperature:.4});return{holonId:e,lensName:t,clusterResolution:o,cellsAnalyzed:Object.keys(l).length,analysis:u,timestamp:Date.now()}}async analyzeGeographicImpact(e,t,n,s={}){if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const i=r.getResolution(t),[o,a]=r.cellToLatLng(t),l=r.cellArea(t,"km2");let c=null;if(i>0){const e=r.cellToParent(t,Math.max(0,i-2));c={holon:e,resolution:i-2,areaKm2:r.cellArea(e,"km2")}}const u=`You are a geographic impact analyst. Analyze the geographic reach and impact of this item.\n\nItem location: ${t}\nResolution: ${i}\nCenter: ${o.toFixed(4)}, ${a.toFixed(4)}\nArea: ${l.toFixed(2)} km²\n\n${c?`Broader region: ${c.areaKm2.toFixed(2)} km²`:""}\n\nAnalyze:\n1. Direct impact area (immediate cell)\n2. Indirect impact area (spillover effects)\n3. Potential reach (if expanded)\n4. Geographic barriers/enablers\n5. Network effects\n\nReturn JSON:\n{\n "directImpact": {\n "areaKm2": n,\n "description": "direct impact area",\n "affectedPopulation": "estimate or N/A"\n },\n "indirectImpact": {\n "estimatedReach": n,\n "mechanisms": ["how impact spreads"],\n "neighboringAreas": ["affected areas"]\n },\n "potentialReach": {\n "ifExpanded": {\n "maxAreaKm2": n,\n "optimalResolution": n,\n "limitingFactors": ["factor1"]\n }\n },\n "geographicFactors": {\n "enablers": ["what helps geographic spread"],\n "barriers": ["what limits spread"]\n },\n "impactScore": {\n "local": 0.0-1.0,\n "regional": 0.0-1.0,\n "network": 0.0-1.0\n },\n "recommendations": ["how to increase impact"],\n "summary": "impact overview"\n}`;return this.llm.getJSON(u,JSON.stringify(e,null,2),{temperature:.3})}}class Io extends Error{constructor(e,t=null){super(e),this.name="AuthorizationError",this.requiredPermission=t}}class Eo extends Error{constructor(e){super(e),this.name="HolosphereError"}}exports.AuthorizationError=Io,exports.Classifier=$o,exports.Council=wo,exports.Embeddings=go,exports.FederationAdvisor=Oo,exports.H3AI=Ro,exports.HoloSphere=class extends m{constructor(e){super(e),this.schemas=new Map,this.subscriptionRegistry=new Be,this._ai=null;const t=e.openaiKey||this._getEnv("OPENAI_API_KEY");if(t){const n={...e.aiOptions,model:e.aiOptions?.model||this._getEnv("HOLOSPHERE_AI_MODEL"),temperature:e.aiOptions?.temperature??this._parseFloat(this._getEnv("HOLOSPHERE_AI_TEMPERATURE"))};this._initializeAI(t,n)}}_getEnv(e){if("undefined"!=typeof process&&process.env)return process.env[e]}_parseFloat(e){if(null==e)return;const t=parseFloat(e);return isNaN(t)?void 0:t}_initializeAI(e,t={}){const n={...t.llm,model:t.model||t.llm?.model,temperature:t.temperature??t.llm?.temperature};this._ai={llm:new po(e,n)};const s=new(0,require("openai").default)({apiKey:e});this._ai.openai=s,this._ai.embeddings=new go(s,this),this._ai.schemaExtractor=new fo(this._ai.llm),this._ai.jsonOps=new mo(this._ai.llm),this._ai.council=new wo(this._ai.llm),this._ai.tts=new vo(s),this._ai.nlQuery=new So(this._ai.llm,this),this._ai.classifier=new $o(this._ai.llm,this),this._ai.spatial=new xo(this._ai.llm,this),this._ai.aggregation=new Ao(this._ai.llm,this),this._ai.federationAdvisor=new Oo(this._ai.llm,this,this._ai.embeddings),this._ai.relationships=new No(this._ai.llm,this,this._ai.embeddings),this._ai.taskBreakdown=new ko(this._ai.llm,this),this._ai.h3ai=new Ro(this._ai.llm,this)}hasAI(){return null!==this._ai}getAIServices(){return this._ai}async toHolon(e,n,s){return function(e,n,s){if("number"!=typeof e||e<-90||e>90)throw new RangeError(`Invalid latitude: ${e}. Must be between -90 and 90.`);if("number"!=typeof n||n<-180||n>180)throw new RangeError(`Invalid longitude: ${n}. Must be between -180 and 180.`);if(!Number.isInteger(s)||s<0||s>15)throw new RangeError(`Invalid resolution: ${s}. Must be integer between 0 and 15.`);try{return t.latLngToCell(e,n,s)}catch(r){throw new Error(`H3 conversion failed: ${r.message}`)}}(e,n,s)}async getParents(e,t){return g(e,t)}async getChildren(e){return function(e){if(!y(e))throw new Error(`Invalid H3 holon ID: ${e}`);try{const n=t.getResolution(e);if(n>=15)throw new Error("Cannot get children of resolution 15 cell (maximum resolution)");return t.cellToChildren(e,n+1)}catch(n){throw new Error(`Failed to get children: ${n.message}`)}}(e)}isValidH3(e){return y(e)}async write(e,t,n,s={}){if(!e||"string"!=typeof e)throw new F("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new F("ValidationError: lensName must be a non-empty string");if(!n||"object"!=typeof n)throw new F("ValidationError: data must be an object");const r=s.capabilityToken||s.capability;if(r){if(!(await this.verifyCapability(r,"write",{holonId:e,lensName:t})))throw new Io("AuthorizationError: Invalid capability token for write operation","write")}n.id||(n.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);const i=k(this.config.appName,e,t,n.id),o=await E(this.client,i);if(o&&!0===o.hologram&&o.target){const e=["hologram","soul","target","id","_meta"],r=Object.keys(o).filter(t=>!e.includes(t)),a={...o},l={};for(const[t,s]of Object.entries(n))e.includes(t)||"_hologram"!==t&&(r.includes(t)?a[t]=s:l[t]=s);if(Object.keys(l).length>0&&!1!==s.validate&&this.schemas.has(t)){const e=k(o.target.appname||this.config.appName,o.target.holonId,o.target.lensName,o.target.dataId),n={...await E(this.client,e),...l},r=this.schemas.get(t),i=void 0!==s.strict?s.strict:r.strict;r.schema&&"object"==typeof r.schema&&!r.schema.$ref&&L(n,r.schema,t,i)}const c=Date.now();if(await I(this.client,i,a),Object.keys(l).length>0){const e=o.target.appname||this.config.appName,t=o.target.holonId,n=o.target.lensName,s=o.target.dataId,r=k(e,t,n,s);await P(this.client,r,l),await Je(this.client,e,t,n,s)}const u=Date.now();return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=u-c,!0}if(n._meta||(n._meta={}),n._meta.timestamp=Date.now(),!1!==s.validate&&this.schemas.has(t)){const e=this.schemas.get(t),r=void 0!==s.strict?s.strict:e.strict;e.schema&&"object"==typeof e.schema&&e.schema.$ref||e.schema&&"object"==typeof e.schema&&L(n,e.schema,t,r)}const a=Date.now(),l=await I(this.client,i,n),c=Date.now();if(l&&(this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=c-a,n._meta&&Array.isArray(n._meta.activeHolograms)&&n._meta.activeHolograms.length>0)){const s=await Je(this.client,this.config.appName,e,t,n.id,n);s.refreshed>0&&await I(this.client,i,s.sourceData)}return l}async _resolveHolograms(e){if(!e)return e;if(Array.isArray(e)){const t=[];for(const n of e){const e=await this._resolveHolograms(n);null!=e&&t.push(e)}return t}if("object"==typeof e){if(!0===e.hologram){const t=await Ie(this.client,e);return t?await this._resolveHolograms(t):null}return e}return e}async read(e,t,n=null,s={}){if(!e||"string"!=typeof e)throw new F("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new F("ValidationError: lensName must be a non-empty string");const r=Date.now();this._metrics.reads++;const i={holonId:e,lensName:t};n&&(i.dataId=n);const o=!1!==s.federated;let a=[this.client.publicKey];if(o)try{const e=await async function(e,t,n={},s="read"){const r=await _e(e,t),i=Date.now(),o=[];for(const a of r.federatedWith)if(a.inboundCapabilities&&0!==a.inboundCapabilities.length)for(const e of a.inboundCapabilities)if(!(e.expires&&e.expires<i)&&(!e.permissions||e.permissions.includes(s))&&me(e.scope,n)){o.push({pubKey:a.pubKey,capability:e});break}return o}(this.client,this.config.appName,i,"read");for(const{pubKey:t}of e)a.includes(t)||a.push(t)}catch(c){console.debug("[read] Federation lookup failed, using local only:",c.message)}const l={authors:a,includeAuthor:!0};if(n){const s=k(this.config.appName,e,t,n),i=await E(this.client,s,l);if(i&&i._deleted){const e=Date.now();return this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=e-r,null}const o=await this._resolveHolograms(i),a=Date.now();return this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=a-r,o}{const n=k(this.config.appName,e,t),s=await C(this.client,n,{...l,hybrid:this.config.hybridMode}),i=await this._resolveHolograms(s),o=Array.isArray(i)?i.filter(e=>!e||!e._deleted):i&&i._deleted?null:i,a=Date.now();return this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=a-r,o}}async update(e,t,n,s,r={}){const i=r.capabilityToken||r.capability;if(i){if(!(await this.verifyCapability(i,"write",{holonId:e,lensName:t})))throw new Io("AuthorizationError: Invalid capability token for update operation","write")}const o=k(this.config.appName,e,t,n),a=await E(this.client,o);if(a&&!0===a.hologram&&a.target){const e=["hologram","soul","target","id","_meta"],t=Object.keys(a).filter(t=>!e.includes(t)),n={},r={};for(const[i,o]of Object.entries(s))e.includes(i)||(t.includes(i)?n[i]=o:r[i]=o);if(Object.keys(n).length>0&&await P(this.client,o,n),Object.keys(r).length>0){const e=k(a.target.appname||this.config.appName,a.target.holonId,a.target.lensName,a.target.dataId);await P(this.client,e,r)}return!0}if(!1!==r.validate&&this.schemas.has(t)){const i={...await this.read(e,t,n),...s},o=this.schemas.get(t),a=void 0!==r.strict?r.strict:o.strict;o.schema&&"object"==typeof o.schema&&o.schema.$ref||o.schema&&"object"==typeof o.schema&&L(i,o.schema,t,a)}return P(this.client,o,s)}async delete(e,t,n,s={}){const r=await this.read(e,t,n);if(!r)return!1;const i=s.capabilityToken||s.capability,o=r._creator||r.owner,a=this.client.publicKey;if(i){if(!(await this.verifyCapability(i,"delete",{holonId:e,lensName:t}))){throw new Io("AuthorizationError: Invalid capability token for delete operation","delete")}}else if(o&&o!==a){throw new Io("AuthorizationError: Delete operation requires capability token","delete")}if(r._meta?.activeHolograms&&Array.isArray(r._meta.activeHolograms)){console.info(`🗑️ Deleting ${r._meta.activeHolograms.length} holograms for ${e}/${t}/${n}`);for(const e of r._meta.activeHolograms)try{const s=k(this.config.appName,e.targetHolon,t,n);await D(this.client,s),console.info(` ✓ Deleted hologram in ${e.targetHolon}`)}catch(c){console.warn(` ⚠️ Failed to delete hologram in ${e.targetHolon}:`,c.message)}}const l=k(this.config.appName,e,t,n);return D(this.client,l)}async writeGlobal(e,t){return q(this.client,this.config.appName,e,t)}async readGlobal(e,t=null){return T(this.client,this.config.appName,e,t)}async updateGlobal(e,t,n){return async function(e,t,n,s,r){return P(e,`${t}/${n}/${s}`,r)}(this.client,this.config.appName,e,t,n)}async deleteGlobal(e,t){return async function(e,t,n,s){return D(e,`${t}/${n}/${s}`)}(this.client,this.config.appName,e,t)}async getAllGlobal(e){return T(this.client,this.config.appName,e)}async deleteAllGlobal(e){return async function(e,t,n){return j(e,`${t}/${n}`)}(this.client,this.config.appName,e)}async getAll(e,t){return this.read(e,t)}async deleteAll(e,t){const n=k(this.config.appName,e,t);return j(this.client,n)}async setSchema(e,t,n=!1){let s=t;if("string"==typeof t&&(s={$ref:t}),!s||"object"!=typeof s&&"boolean"!=typeof s)throw new F("Schema must be a valid JSON Schema object or boolean");if(!("object"!=typeof s||s.$ref||s.type||s.properties||s.items||!0===s||!1===s))throw new F("ValidationError: Invalid JSON Schema format - must have type, properties, or items");this.schemas.set(e,{schema:s,strict:n})}async getSchema(e){const t=this.schemas.get(e);return t?t.schema:null}async clearSchema(e){this.schemas.delete(e),function(e){H.delete(e)}(e)}async federate(e,t,n,s={}){if(e===t)throw new Error("Cannot federate a holon with itself");if(s.direction&&!["inbound","outbound","bidirectional"].includes(s.direction))throw new Error("Invalid federation direction - must be inbound, outbound, or bidirectional");if("bidirectional"===s.direction){const{direction:r,...i}=s,o=await this.federate(e,t,n,{...i,direction:"outbound"}),a=await this.federate(e,t,n,{...i,direction:"inbound"});return o&&a}const r=await async function(e,t,n,s,r,i={}){const{direction:o="outbound",mode:a="reference"}=i,l={sourceHolon:n,targetHolon:s,lensName:r,direction:o,mode:a,created:Date.now()};return I(e,k(t,n,r,"_federation"),l)}(this.client,this.config.appName,e,t,n,s);if(r){this._metrics.federations||(this._metrics.federations=0),this._metrics.federations++;if(!(!1!==s.propagateExisting))return r;const i=s.direction||"outbound",o=s.mode||"reference",a=s.filter;if("outbound"===i){const s=await this.getFederation(t),r=s?.lensConfig?.[e];if(r&&r.inbound&&!r.inbound.includes(n))console.log(`Skipping outbound propagation - ${t} doesn't accept lens '${n}' in inbound from ${e}`);else{const s=k(this.config.appName,e,n),r=await C(this.client,s),i=Array.isArray(r)?r:r?[r]:[];for(const l of i)"_federation"!==l.id&&!0!==l.hologram&&(l._meta&&l._meta.source&&l._meta.source!==e||a&&!a(l)||await Ee(this.client,this.config.appName,l,e,t,n,o))}}if("inbound"===i){const s=await this.getFederation(e),r=s?.lensConfig?.[t];if(r&&r.inbound&&!r.inbound.includes(n))console.log(`Skipping inbound propagation - ${e} doesn't accept lens '${n}' in inbound from ${t}`);else{const s=k(this.config.appName,t,n),r=await C(this.client,s),i=Array.isArray(r)?r:r?[r]:[];for(const l of i)"_federation"!==l.id&&!0!==l.hologram&&(l._meta&&l._meta.source&&l._meta.source!==t||a&&!a(l)||await Ee(this.client,this.config.appName,l,t,e,n,o))}}}return r}async getFederatedData(e,t,n={}){const{resolveHolograms:s=!0}=n;if(s){const n=await this.read(e,t);return(Array.isArray(n)?n:n?[n]:[]).filter(e=>null!=e&&"_federation"!==e.id)}{const n=k(this.config.appName,e,t),s=await C(this.client,n);return(Array.isArray(s)?s:s?[s]:[]).filter(e=>null!=e&&"_federation"!==e.id)}}async unfederate(e,t,n){const s=k(this.config.appName,e,n,"_federation");return await D(this.client,s),!0}async updateHologramOverrides(e,t,n,s){return Ce(this.client,this.config.appName,e,t,n,s)}createHologram(e,t,n,s=null){if(!n||!n.id)throw new Error("createHologram: data must have an id property");return Re(e,0,t,n.id,this.config.appName)}async getActiveHolograms(e,t,n){const s=await this.read(e,t,n);return s&&s._meta&&Array.isArray(s._meta.activeHolograms)?s._meta.activeHolograms:[]}async removeActiveHologram(e,t,n,s){return Te(this.client,this.config.appName,e,t,n,s)}async deleteHologram(e,t,n,s={}){return He(this.client,this.config.appName,e,t,n,s)}async propagateData(e,t,n,s,r={}){const{mode:i="reference"}=r;return Ee(this.client,this.config.appName,e,t,n,s,i)}async resolveHologram(e){return Ie(this.client,e)}isHologram(e){return Pe(e)}isResolvedHologram(e){return De(e)}getHologramSource(e){return je(e)}async cleanupCircularHolograms(e,t,n={}){return Fe(this.client,this.config.appName,e,t,n)}async cleanupCircularHologramsByIds(e,t,n,s={}){return Le(this.client,this.config.appName,e,t,n,s)}async propagate(e,t,n,s={}){const{useHolograms:r=!0,propagateToParents:i=!1,maxParentLevels:o=3}=s,a={success:0,failed:0,targets:[],parentPropagation:null},l=await this.getFederation(e);if(l&&l.outbound)for(const u of l.outbound){const s=l.lensConfig?.[u];if(!s||!s.outbound||s.outbound.includes(t)){try{const n=await this.getFederation(u),s=n?.lensConfig?.[e];if(s&&s.inbound&&!s.inbound.includes(t)){console.log(`Skipping propagation to ${u} - lens '${t}' not in their inbound config for ${e}`);continue}}catch(c){console.warn(`Could not verify receiver's inbound config for ${u}, proceeding anyway:`,c)}try{const s=r?"reference":"copy";await Ee(this.client,this.config.appName,n,e,u,t,s),a.success++,a.targets.push(u)}catch(c){console.error(`Failed to propagate to ${u}:`,c),a.failed++}}}if(i&&y(e)){const s=g(e).slice(0,o);a.parentPropagation={success:0,failed:0,targets:[]};for(const i of s)try{const s=r?"reference":"copy";await Ee(this.client,this.config.appName,n,e,i,t,s),a.parentPropagation.success++,a.parentPropagation.targets.push(i)}catch(c){console.error(`Failed to propagate to parent ${i}:`,c),a.parentPropagation.failed++}}return a}async getFederation(e){if(!e)throw new Error("getFederation: Missing holon ID");const t=await this.getGlobal("federation",e);if(!t)return null;if(Array.isArray(t.inbound)||(t.inbound=[]),Array.isArray(t.outbound)||(t.outbound=[]),t.lensConfig&&"object"==typeof t.lensConfig||(t.lensConfig={}),!Array.isArray(t.federated)){const e=new Set([...t.inbound,...t.outbound]);t.federated=Array.from(e)}return t}async federateHolon(e,t,n={}){const{lensConfig:s={inbound:[],outbound:[]}}=n;if(e===t)throw new Error("Cannot federate a holon with itself");let r=await this.getGlobal("federation",e)||{id:e,name:e,federated:[],inbound:[],outbound:[],lensConfig:{},timestamp:Date.now()};Array.isArray(r.federated)||(r.federated=[]),Array.isArray(r.inbound)||(r.inbound=[]),Array.isArray(r.outbound)||(r.outbound=[]),r.lensConfig&&"object"==typeof r.lensConfig||(r.lensConfig={}),r.federated.includes(t)||r.federated.push(t),s.outbound&&s.outbound.length>0?r.outbound.includes(t)||r.outbound.push(t):r.outbound=r.outbound.filter(e=>e!==t),s.inbound&&s.inbound.length>0?r.inbound.includes(t)||r.inbound.push(t):r.inbound=r.inbound.filter(e=>e!==t),r.lensConfig[t]={inbound:s.inbound||[],outbound:s.outbound||[],timestamp:Date.now()};const i=await this.writeGlobal("federation",r);if(this.clearCache("federation"),i){for(const n of s.inbound||[])await this.federate(t,e,n,{direction:"outbound",mode:"reference"});for(const n of s.outbound||[])await this.federate(e,t,n,{direction:"outbound",mode:"reference"})}return i}async unfederateHolon(e,t){const n=await this.getGlobal("federation",e);if(!n)return!1;const s=n.lensConfig?.[t];n.federated=(n.federated||[]).filter(e=>e!==t),n.inbound=(n.inbound||[]).filter(e=>e!==t),n.outbound=(n.outbound||[]).filter(e=>e!==t),n.lensConfig&&delete n.lensConfig[t];const r=await this.writeGlobal("federation",n);if(this.clearCache("federation"),r&&s){for(const n of s.inbound||[])await this.unfederate(t,e,n);for(const n of s.outbound||[])await this.unfederate(e,t,n)}return r}async getFederatedConfig(e,t){const n=await this.getGlobal("federation",e);return n&&n.lensConfig&&n.lensConfig[t]||null}async upcast(e,t,n,s={}){return Ke(this.client,this.config.appName,e,t,n,s)}subscribe(e,t,n,s={}){if("function"!=typeof n)throw new TypeError("callback must be a function");const r=k(this.config.appName,e,t),i={realtimeOnly:!0,...s},o=`${e}-${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;let a=null,l=!1;return Me(this.client,r,n,i).then(e=>{a=e,l?e.unsubscribe():this.subscriptionRegistry.register(o,e)}).catch(e=>{this._log("ERROR","Subscription setup failed",{path:r,error:e.message})}),this._metrics.subscriptions++,{unsubscribe:()=>{l=!0,a&&this.subscriptionRegistry.unregister(o)}}}async subscribeGlobal(e,t,n,s={}){if("function"!=typeof n)throw new TypeError("callback must be a function");const r=`${this.config.appName}/${e}/${t}`,i={realtimeOnly:!0,...s},o=await Me(this.client,r,n,i),a=`global-${e}-${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return this.subscriptionRegistry.register(a,o),this._metrics.subscriptions++,{unsubscribe:()=>{this.subscriptionRegistry.unregister(a)}}}async getPublicKey(e){return async function(e){return Y((await pe()).getPublicKey(e))}(e)}async sign(e,t){return fe(e,t)}async verify(e,t,n){return async function(e,t,n){try{if(!n||"string"!=typeof n||n.length<64)throw new Error("Invalid public key format");const s=await pe(),r=we(e);return s.verify(t,r,n)}catch(s){if("Invalid public key format"===s.message)throw s;return!1}}(e,t,n)}async issueCapability(e,t,n,s){return ge(e,t,n,s)}async verifyCapability(e,t,n){return ye(e,t,n)}async publishNostr(e,t,n="social"){if(function(e,t=!0,n=!1){if(!e||"object"!=typeof e){if(n)throw new F("ValidationError: Invalid Nostr event format");return!1}if("number"!=typeof e.kind){if(n)throw new F("ValidationError: Invalid Nostr event format - kind must be a number");return!1}if(!Array.isArray(e.tags)){if(n)throw new F("ValidationError: Invalid Nostr event format - tags must be an array");return!1}if("string"!=typeof e.content){if(n)throw new F("ValidationError: Invalid Nostr event format - content must be a string");return!1}if("number"!=typeof e.created_at){if(n)throw new F("ValidationError: Invalid Nostr event format - created_at must be a number");return!1}if(!t){if("string"!=typeof e.id){if(n)throw new F("ValidationError: Invalid Nostr event format - id must be a string");return!1}if("string"!=typeof e.pubkey){if(n)throw new F("ValidationError: Invalid Nostr event format - pubkey must be a string");return!1}if("string"!=typeof e.sig){if(n)throw new F("ValidationError: Invalid Nostr event format - sig must be a string");return!1}}}(e,!0,!0),!e.id||!e.pubkey||!e.sig){const{finalizeEvent:t}=await import("nostr-tools"),n=t(e,this.client.privateKey);e.id=n.id,e.pubkey=n.pubkey,e.sig=n.sig}const s=function(e){const t=e.id||`nostr-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=e.pubkey||"anonymous",s=e.sig||"";return{id:t,protocol:"nostr",originalFormat:"nip-01",pubkey:n,sig:s,created_at:e.created_at,kind:e.kind,tags:JSON.stringify(e.tags),content:e.content,signature:s,_meta:{timestamp:1e3*e.created_at,protocol:"nostr"}}}(e);return this.write(t,n,s)}async publishActivityPub(e,t,n="social"){!function(e,t=!1,n=!1){if(!e||"object"!=typeof e){if(t)throw new F("ValidationError: Invalid ActivityPub object format");return!1}if(!e["@context"]){if(t)throw new F("ValidationError: Invalid ActivityPub object format - @context is required");return!1}if("string"!=typeof e.type){if(t)throw new F("ValidationError: Invalid ActivityPub object format - type must be a string");return!1}if(n&&"string"!=typeof e.id){if(t)throw new F("ValidationError: Invalid ActivityPub object format - id must be a string");return!1}}(e,!0);const s=function(e){const t=e.id||`ap-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return{id:t,protocol:"activitypub",type:e.type,actor:e.actor,published:e.published,content:e.content||e.name,originalObject:{...e,id:t},_meta:{timestamp:e.published?new Date(e.published).getTime():Date.now(),protocol:"activitypub"}}}(e);return this.write(t,n,s)}async querySocial(e,t={}){const{protocol:n,accessLevel:s}=t;let r=await this.read(e,"social");return n&&(r=function(e,t){return t&&"all"!==t?Array.isArray(e)?e.filter(e=>e.protocol===t):[]:e}(r,n)),s&&(r=function(e,t){return t?e.filter(e=>!e.accessLevel||e.accessLevel===t):e}(r,s)),Array.isArray(r)&&(r=r.map(e=>"nostr"===e.protocol&&"string"==typeof e.tags?{...e,tags:JSON.parse(e.tags)}:e)),r}async verifyNostrEvent(e){const{verifyEvent:t}=await import("nostr-tools");return t({...e,tags:"string"==typeof e.tags?JSON.parse(e.tags):e.tags})}metrics(){return{...super.metrics(),federations:this._metrics.federations||0,avgWriteTime:this._metrics.writes>0?(this._metrics.totalWriteTime||0)/this._metrics.writes:0,avgReadTime:this._metrics.reads>0?(this._metrics.totalReadTime||0)/this._metrics.reads:0}}async put(e,t,n,s={}){return this.write(e,t,n,s)}async get(e,t,n=null,s={}){return this.read(e,t,n,s)}async remove(e,t,n,s={}){return this.delete(e,t,n,s)}async putGlobal(e,t){return this.writeGlobal(e,t)}async getGlobal(e,t=null){return this.readGlobal(e,t)}async removeGlobal(e,t){return this.deleteGlobal(e,t)}async defineSchema(e,t,n=!1){return this.setSchema(e,t,n)}async fetchSchema(e){return this.getSchema(e)}async removeSchema(e){return this.clearSchema(e)}async store(e,t,n,s={}){return this.write(e,t,n,s)}async fetch(e,t,n=null,s={}){return this.read(e,t,n,s)}async save(e,t,n,s={}){return this.write(e,t,n,s)}async load(e,t,n=null,s={}){return this.read(e,t,n,s)}clearCache(e=null){this.client&&this.client.clearCache&&this.client.clearCache(e)}_requireAI(){if(!this._ai)throw new Error("AI services not initialized. Provide openaiKey in config.")}async summarize(e,t={}){return this._requireAI(),this._ai.llm.summarize(e,t)}async analyze(e,t,n={}){return this._requireAI(),this._ai.llm.analyze(e,t,n)}async extractKeywords(e,t={}){return this._requireAI(),this._ai.llm.extractKeywords(e,t)}async categorize(e,t,n={}){return this._requireAI(),this._ai.llm.categorize(e,t,n)}async translate(e,t,n={}){return this._requireAI(),this._ai.llm.translate(e,t,n)}async generateQuestions(e,t={}){return this._requireAI(),this._ai.llm.generateQuestions(e,t)}async extractToSchema(e,t,n={}){this._requireAI();const s=await this.getSchema(t);if(!s)throw new Error(`No schema found for lens: ${t}`);return this._ai.schemaExtractor.extractToSchema(e,s,n)}async jsonAdd(e,t,n={}){return this._requireAI(),this._ai.jsonOps.add(e,t,n)}async jsonSubtract(e,t,n={}){return this._requireAI(),this._ai.jsonOps.subtract(e,t,n)}async jsonUnion(e,t,n={}){return this._requireAI(),this._ai.jsonOps.union(e,t,n)}async jsonDifference(e,t,n={}){return this._requireAI(),this._ai.jsonOps.difference(e,t,n)}async jsonConcatenate(e,t,n={}){return this._requireAI(),this._ai.jsonOps.concatenate(e,t,n)}async embed(e){return this._requireAI(),this._ai.embeddings.embed(e)}async semanticSearch(e,t,n,s={}){return this._requireAI(),this._ai.embeddings.semanticSearch(e,t,n,s)}async storeWithEmbedding(e,t,n,s="description"){return this._requireAI(),this._ai.embeddings.storeWithEmbedding(e,t,n,s)}async askCouncil(e,t={}){return this._requireAI(),this._ai.council.ask(e,t)}async askCouncilCustom(e,t,n={}){return this._requireAI(),this._ai.council.askCustom(e,t,n)}async textToSpeech(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speak(e,t,n)}async textToSpeechBase64(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speakBase64(e,t,n)}async nlQuery(e,t=null,n=null,s={}){return this._requireAI(),this._ai.nlQuery.execute(e,t,n,s)}async parseNLQuery(e){return this._requireAI(),this._ai.nlQuery.parse(e)}async classifyToLens(e,t={}){return this._requireAI(),this._ai.classifier.classifyToLens(e,t)}async autoStore(e,t,n={}){return this._requireAI(),this._ai.classifier.autoStore(e,t,n)}registerLensForClassification(e,t,n=[]){this._requireAI(),this._ai.classifier.registerLens(e,t,n)}async analyzeRegion(e,t=null,n=null,s={}){return this._requireAI(),this._ai.spatial.analyzeRegion(e,t,n,s)}async compareRegions(e,t,n=null){return this._requireAI(),this._ai.spatial.compareRegions(e,t,n)}async spatialTrends(e,t,n=null){return this._requireAI(),this._ai.spatial.spatialTrends(e,t,n)}async smartUpcast(e,t,n={}){return this._requireAI(),this._ai.aggregation.smartUpcast(e,t,n)}async generateHolonSummary(e){return this._requireAI(),this._ai.aggregation.generateHolonSummary(e)}async suggestFederations(e,t={}){return this._requireAI(),this._ai.federationAdvisor.suggestFederations(e,t)}async analyzeFederationHealth(e){return this._requireAI(),this._ai.federationAdvisor.analyzeFederationHealth(e)}async optimizeFederation(e){return this._requireAI(),this._ai.federationAdvisor.optimizeFederation(e)}async discoverRelationships(e,t=null){return this._requireAI(),this._ai.relationships.discoverRelationships(e,t)}async findSimilar(e,t,n=null,s={}){return this._requireAI(),this._ai.relationships.findSimilar(e,t,n,s)}async buildRelationshipGraph(e,t){return this._requireAI(),this._ai.relationships.buildGraph(e,t)}async suggestConnections(e,t,n){return this._requireAI(),this._ai.relationships.suggestConnections(e,t,n)}async breakdown(e,t,n,s={}){return this._requireAI(),this._ai.taskBreakdown.breakdown(e,t,n,s)}async suggestBreakdownStrategy(e){return this._requireAI(),this._ai.taskBreakdown.suggestStrategy(e)}flattenBreakdown(e){return this._requireAI(),this._ai.taskBreakdown.flatten(e)}getBreakdownDependencyOrder(e){return this._requireAI(),this._ai.taskBreakdown.getDependencyOrder(e)}async getBreakdownProgress(e,t,n){return this._requireAI(),this._ai.taskBreakdown.getProgress(e,t,n)}async suggestH3Resolution(e,t={}){return this._requireAI(),this._ai.h3ai.suggestResolution(e,t)}async analyzeH3Distribution(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeDistribution(e,t,n)}async findH3NeighborRelevance(e,t,n={}){return this._requireAI(),this._ai.h3ai.findNeighborRelevance(e,t,n)}async suggestGeographicScope(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestGeographicScope(e,t,n,s)}async analyzeH3Coverage(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeCoverage(e,t,n)}async crossH3ResolutionInsights(e,t,n={}){return this._requireAI(),this._ai.h3ai.crossResolutionInsights(e,t,n)}async suggestH3Migration(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestMigration(e,t,n,s)}async generateH3Report(e,t={}){return this._requireAI(),this._ai.h3ai.generateGeographicReport(e,t)}async findH3Clusters(e,t,n={}){return this._requireAI(),this._ai.h3ai.findGeographicClusters(e,t,n)}async analyzeH3Impact(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.analyzeGeographicImpact(e,t,n,s)}async addFederatedHolosphere(e,t={}){if(!e||"string"!=typeof e)throw new F("pubKey must be a valid public key string");return Se(this.client,this.config.appName,e,t)}async removeFederatedHolosphere(e){return $e(this.client,this.config.appName,e)}async getFederatedHolospheres(){return xe(this.client,this.config.appName)}async getFederationRegistry(){return _e(this.client,this.config.appName)}async storeInboundCapability(e,t){return Oe(this.client,this.config.appName,e,t)}async readFromFederatedSource(e,t,n,s=null){const r=await Ae(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!r)throw new Io("No valid capability for federated source","read");if(!(await this.verifyCapability(r.token,"read",{holonId:t,lensName:n,dataId:s})))throw new Io("Capability verification failed","read");if(s){const r=k(this.config.appName,t,n,s);return _(this.client,r,3e4,{authors:[e],includeAuthor:!0})}{const s=k(this.config.appName,t,n);return v(this.client,s,3e4,{authors:[e],includeAuthor:!0})}}async createCrossHolosphereHologram(e,t,n,s,r,i={}){const{embedCapability:o=!0}=i,a=await Ae(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!a)throw new Io("No valid capability for cross-holosphere hologram","read");const l=Re(t,0,n,s,this.config.appName,{authorPubKey:e,capability:o?a.token:null}),c=k(this.config.appName,r,n,s);return await I(this.client,c,l),l}async issueCapabilityForFederation(e,t,n,s={}){const{expiresIn:r=36e5,trackInRegistry:i=!0}=s,o=await ge(n,t,e,{expiresIn:r,issuerKey:this.client.privateKey});if(i){await async function(e,t,n){return(await _e(e,t)).federatedWith.find(e=>e.pubKey===n)||null}(this.client,this.config.appName,e)||await Se(this.client,this.config.appName,e,{addedVia:"capability_issued"}),await Ne(this.client,this.config.appName,e,{tokenHash:await this._hashToken(o),scope:t,permissions:n,expires:Date.now()+r})}return o}async _hashToken(e){const{sha256:t}=await Promise.resolve().then(()=>he),{bytesToHex:n}=await Promise.resolve().then(()=>te);return n(t((new TextEncoder).encode(e)))}async sendFederationRequest(e,t={}){return Ve(this.client,this.config.appName,e,t)}async subscribeFederationRequests(e){return Ge(this.client,e)}async acceptFederationRequest(e,t={}){return Ye(this.client,this.config.appName,e,t)}async declineFederationRequest(e,t=""){return Xe(this.client,this.config.appName,e,t)}async subscribeFederationAcceptances(e){return Qe(this.client,this.config.appName,e)}async subscribeFederationDeclines(e){return Ze(this.client,e)}async getPendingFederationRequests(e={}){return et(this.client,e)}},exports.HolosphereError=Eo,exports.JSONOps=mo,exports.LLMService=po,exports.MODELS=_o,exports.NLQuery=So,exports.PersistentStorage=class{async init(e){throw new Error("init() must be implemented by subclass")}async put(e,t){throw new Error("put() must be implemented by subclass")}async get(e){throw new Error("get() must be implemented by subclass")}async getAll(e){throw new Error("getAll() must be implemented by subclass")}async delete(e){throw new Error("delete() must be implemented by subclass")}async clear(){throw new Error("clear() must be implemented by subclass")}async close(){throw new Error("close() must be implemented by subclass")}},exports.RelationshipDiscovery=No,exports.SchemaExtractor=fo,exports.SmartAggregation=Ao,exports.SpatialAnalysis=xo,exports.TTS=vo,exports.TaskBreakdown=ko,exports.VOICES=bo,exports.ValidationError=F,exports.acceptFederationRequest=Ye,exports.addActiveHologram=qe,exports.addFederatedPartner=Se,exports.cleanupCircularHolograms=Fe,exports.cleanupCircularHologramsByIds=Le,exports.cleanupExpiredCapabilities=async function(e,t){const n=await _e(e,t),s=Date.now();let r=0,i=0;for(const o of n.federatedWith){if(o.inboundCapabilities){const e=o.inboundCapabilities.length;o.inboundCapabilities=o.inboundCapabilities.filter(e=>!e.expires||e.expires>s),r+=e-o.inboundCapabilities.length}if(o.outboundCapabilities){const e=o.outboundCapabilities.length;o.outboundCapabilities=o.outboundCapabilities.filter(e=>!e.expires||e.expires>s),i+=e-o.outboundCapabilities.length}}return(r>0||i>0)&&await ve(e,t,n),{inboundRemoved:r,outboundRemoved:i}},exports.createAIServices=function(e,t=null,n={},s=null){const r=new po(e,n.llm),i=s,o=new go(i,t);return{llm:r,openai:i,embeddings:o,schemaExtractor:new fo(r),jsonOps:new mo(r),council:new wo(r),tts:new vo(i),nlQuery:new So(r,t),classifier:new $o(r,t),spatial:new xo(r,t),aggregation:new Ao(r,t),federationAdvisor:new Oo(r,t,o),relationships:new No(r,t,o),taskBreakdown:new ko(r,t),h3ai:new Ro(r,t)}},exports.createHologram=Re,exports.declineFederationRequest=Xe,exports.deleteHologram=He,exports.getCapabilityForAuthor=Ae,exports.getFederatedAuthors=xe,exports.getFederationRegistry=_e,exports.getHologramSource=je,exports.getPendingFederationRequests=et,exports.isHologram=Pe,exports.isResolvedHologram=De,exports.matchScope=me,exports.nostrAsync=N,exports.propagateData=Ee,exports.refreshActiveHolograms=Je,exports.removeActiveHologram=Te,exports.removeFederatedPartner=$e,exports.resolveHologram=Ie,exports.sendFederationRequest=Ve,exports.storeInboundCapability=Oe,exports.storeOutboundCapability=Ne,exports.subscribeFederationAcceptances=Qe,exports.subscribeFederationDeclines=Ze,exports.subscribeFederationRequests=Ge,exports.updateHologramOverrides=Ce;
|
|
3
|
-
//# sourceMappingURL=index-ifOgtDvd.cjs.map
|